Domanda

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(""); 
            }
        }
    });
}
È stato utile?

Soluzione

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("");
    }
});

Altri suggerimenti

You can't modify the textfield's doucment inside a DocumentListener. Use a DocumentFilter to modify text.

Document listeners should not modify the contents of the document; The change is already complete by the time the listener is notified of the change. Instead, write a custom document that overrides the insertString or remove methods, or both.

In another part.

You may want to change the document's text within a document listener. However, you should never modify the contents of a text component from within a document listener. If you do, the program will likely deadlock. Instead, you can use a formatted text field or provide a document filter.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top