2016-09-21 110 views
0

我使用條碼掃描器掃描產品條碼。 12位數字將顯示在JTextfield中。 getText()將採用該12位數字查找其對應項目,並增加項目數量。我的問題是如何在掃描新項目之前擦除JTextfield中的文本。所以getText()方法可以採取新的12位數字。我試着在監聽器中添加setText(""),我知道這不是正確的方法。java中的條碼掃描

任何幫助將不勝感激,謝謝!

enter image description here

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) 
+0

'如何在新項目被掃描前擦除JTextfield中的文本'爲什麼需要擦除,新條形碼項目不能替換? – copeg

+0

每次我掃描,新的條碼項目將追加到文本字段。如果有辦法取代,那也是好的。 –

回答

0

我的問題是使用的DocumentFilter解決。謝謝!