Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't clear jtextfield using Documentlistener

i have a textfield, when the user inserts a certain number of characters the program should put it in a JTable and clears the textfield, but it fires an event for Jtextfield.setText("");

Here's my code:

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

        @Override
        public void insertUpdate(DocumentEvent e) {
            printIt();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {

        }

        @Override
        public void changedUpdate(DocumentEvent e) {

        }

        private void printIt() {
            //DocumentEvent.EventType type = documentEvent.getType();
            String code=jTextField2.getText().trim();

           // if(type.toString().trim().length()==13)
            if (code.length()==4) {
                   list.add(code);
                   mod.addRow(new Object[]{code});
                   jTextField2.setText(""); 
            }
        }
    });
}
like image 333
Arshtat Avatar asked Dec 25 '22 19:12

Arshtat


1 Answers

To update the text field while using a DocumentListener you need to wrap the code in a SwingUtilities.invokeLater() so the code is executed after all updates have been done to the Document.

SwingUtilities.invokeLater(new Runnable()
{
    public void run()
    {
        jTextField2.setText("");
    }
});
like image 172
camickr Avatar answered Dec 28 '22 11:12

camickr