Link to home
Start Free TrialLog in
Avatar of BinaryFlusher
BinaryFlusher

asked on

Clear jTextfield when using DocumentListener

Hi

I am using a barcode scanner to enter text into a jTextfield, then using a DocumentListener (insertUpdate method) to detect inserted text in this field. When this is triggered it selectes the current item in a jComboBox, based on the text data in the jTextField, which in turn adds the current selected item onto a table.

The above functionality works, but the issue I have is that, although the text field regains focus, I cannot get the text field to be cleared of text, so that when another barcode is read it is not appended to the end of the current data.

Can you advise, with a code snippet, how I can clear the textfield ot its data after an event is registered and the action taken in the combobox and table. I have tried adding a foo.setSelectedText("") on the text field but this stops the above functionality from working.

Should I use an additonal listener on the text field? But how would I stop this from triggering before the DocumtnListener has actioned based on the current text in the field.

Code for the DocumentListener...

        main.tillPanel.txtBarcode.getDocument().addDocumentListener(new DocumentListener() {

            public void removeUpdate(DocumentEvent e) {
            }
            public void changedUpdate(DocumentEvent e) {
            }

            public void insertUpdate(DocumentEvent e) {

                String selectedBarcodeItem = main.tillPanel.txtBarcode.getText();
                for (int d = 0; d < roundStockObj.length; d++) {
                    if (roundStockObj[d].getBarcode().equals(selectedBarcodeItem)) {
                           
                   main.tillPanel.cmbTillProdSelect.setSelectedItem(roundStockObj[d].getDescription());
                        break;
                    }
                }
         }
});

Thanks in advance
Avatar of for_yan
for_yan
Flag of United States of America image

you just say jTexctFiled.setText("")

why set selected text?

I was always using just ActionListener in such cases
and it worked without problems.
You need to have the scanner configured that it should send carriage return after waht it is reading
Then of course I set
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ActionListener will trigger only after it receives carriage return
(this is different from KeyListener, which will trigger all the time and you don't want it in this case)
Avatar of BinaryFlusher
BinaryFlusher

ASKER

for_yan

Many thanks, have done as you explained and works a treat.

Avatar of CEHJ
Why were you using a DocumentListener in the first place?
You are always welcome.