averageman
averageman

Reputation: 923

Listeners and their objects

I have a JTextField with a listener for a change-text event.

Can I use this listener to affect the same object it is listening to? For instance, if it detects a "problematic" change, it should delete all the text in that same JTextField object.

Is this possible? It doesn't seem to work...

An example is as follows: .

this.txtSearch.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
    validate();
}

public void removeUpdate(DocumentEvent e) {
    validate();
}

public void insertUpdate(DocumentEvent e) {
    validate();
}

private void validate(){
    if not_good(txtSearch.getText()) {
        txtSearch.setText("");
    }
}

Upvotes: 0

Views: 69

Answers (2)

mKorbel
mKorbel

Reputation: 109813

  • for JTextComponent you have to use proper methods that have got access to the its Model

  • Document is Model for JTextComponent

for output from keyboard you have got two choices

  • for output from JTextComponent to outside (to another element(s) in the Swing GUI) use DocumentListener

  • for changes / filtering / modify inside JTextComponent to use DocumentFilter

Upvotes: 1

npe
npe

Reputation: 15699

Changing text in JTextField from a textChanged event is likely to cause a (possibly infinite) loop of textChanged events. Do not do that.

If you want to validate input to a JTextField rather use InputVerifier.

The javadoc contains some examples of how to use it, have a look.

Upvotes: 2

Related Questions