首页 > 解决方案 > 条码扫描仪逐个字符

问题描述

我已经尝试了一段时间,但无法找到一种仅在条形码扫描仪完成扫描后才能将文本从文本框中取出的方法。我正在使用 Swing 框架和 Java。如果将文本粘贴 (Ctrl + V) 到 JTextbox 中,则我的代码可以工作,但条形码扫描仪无法正常工作,因为我的方法依次针对条形码的每几个字符运行。

这是我的代码:

public class pos extends javax.swing.JFrame{
private Timer updateTimer;
private ResultSet data;
ResultSet rs = null;
PreparedStatement pst = null;

public pos() {
    initComponents();
    this.setLocationRelativeTo(null);
    Function f = new Function();

            updateTimer = new Timer(10, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) { 
                ResultSet rs = null;
                rs = f.find(prodID.getText());
                data = rs;
                }
            });
            updateTimer.setRepeats(false);

    prodID.getDocument().addDocumentListener(new DocumentListener(){

        @Override
        public void insertUpdate(DocumentEvent arg0){
            warn();
        }
        @Override
        public void removeUpdate(DocumentEvent arg0){ 
            warn();
        }
        @Override
        public void changedUpdate(DocumentEvent arg0){
            warn();
        }          

    });


}

protected void warn(){
            try{
                if(this.data.next()){
                    prodName.setText(this.data.getString("prodName"));
                    priceField.setText(String.valueOf(new Double(this.data.getString("price"))));
                }else{
                    JOptionPane.showMessageDialog(null, "No Data for this ID");
                }
            }catch(Exception ex)
            {
                JOptionPane.showMessageDialog(null, ex);
            }
            updateTimer.restart();
        }

public Connection getConnection(){
    Connection con = null;
    try{
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/fmgaccount","root","");
    }catch(Exception ex){

    }
    return con;
}



public class Function{
    Connection con = null;
    public ResultSet find(String s){
        try{
        con = getConnection();
        pst = con.prepareStatement("SELECT prodName, price FROM deliverystocks WHERE prodID=?");
        pst.setString(1,s);
        rs = pst.executeQuery();
        }catch(Exception ex)
                {
                   JOptionPane.showMessageDialog(null, ex);
                }
         return rs;
    }

}

标签: javaswingdocumentlistener

解决方案


推荐阅读