简体   繁体   中英

Barcode scan in java

I use barcode scanner to scan a product barcode. 12 digit number will display in JTextfield. getText() will take that 12 digit number to find its corresponding item, and increment item quantity. My problem is how to erase the text in the JTextfield before new item been scanned. So getText() method can take new 12 digit number. I tried add setText("") in the Listener which I know is not the correct way.

Any help would be greatly appreciated, Thanks!

在此处输入图片说明

barcodeTextField.getDocument().addDocumentListener(new DocumentListener(){
   public void changedUpdate(DocumentEvent e) {
       try {
           doSomething();
        } catch (SQLException e1) {
           e1.printStackTrace();
        }
   }

   public void insertUpdate(DocumentEvent e) {
       try {
           doSomething();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
   }
   public void removeUpdate(DocumentEvent e) {
       try {
            doSomething();
       } catch (SQLException e1) {
            e1.printStackTrace();
       }
   }

   public void doSomething() throws SQLException{
      String itemName="";
      for(Item eachItem: results){
         if(Long.parseLong(barcodeTextField.getText())==eachItem.getUPC()){
            itemName = eachItem.getItemName();
            itemTextField.setText(eachItem.getItemName());
            //barcodeTextField.setText("");
            break;
           }                        
      }

      for(int i=0;i<model.getRowCount();i++){
          if(itemName.equals(model.getValueAt(i, 1).toString())){
             System.out.println("Item found");
             model.incrementQuantity(i);
           }
      }
    }});


Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException:      Attempt to mutate in notification
at javax.swing.text.AbstractDocument.writeLock(Unknown Source)
at javax.swing.text.AbstractDocument.replace(Unknown Source)
at javax.swing.text.JTextComponent.setText(Unknown Source)

My problem is solved by using DocumentFilter. Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM