Sunday, October 10, 2010

Listen when the text is changed on a JTextField (Java 6 Swing)

I wanted to listen and execute some actions every time the text was changed on a JTextField. I found a very useful post on this link.

http://www.velocityreviews.com/forums/t136479-jtextfield-cant-listen-when-the-text-is-changed.html

Here is the code I'm using, thanks a lot Mark McMillan.

You want to listen for changes on the Document that is associated
with the TextField. If you don't explicitly create a Document the
TextField does it for you. To setup a listener:

// Listen for changes in the text
myTextField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
// text was changed
}
public void removeUpdate(DocumentEvent e) {
// text was deleted
}
public void insertUpdate(DocumentEvent e) {
// text was inserted
}
});

Note this works no matter how the text gets changed; via a
clipboard cut/paste, progamatic "setText()" on the TextField,
or the user typing into the field on the UI.

No comments: