Philip Morris
Philip Morris

Reputation: 469

Change Listener for a JTextfield

I made a program that dynamically gets data from a Panel but my code needs the user to hit the enter button for the data to be updated. Is there a change listener or other listeners that can update the data from a Jtextfield whenever it is updated? Thanks!

Upvotes: 2

Views: 8494

Answers (2)

Andrey Megvinov
Andrey Megvinov

Reputation: 459

As already said - use DocumentListener to track changes on the jTextField, however, because of DocumentListener is kind of "overengineered", and there are very few use cases where you must distinguish between different types of changes (insertUpdate, removeUpdate and changedUpdate), what you can do is:

crate an interface that extends DocumentListener and provide default implemetation of all DocumentListener methods:

@FunctionalInterface
public interface SimpleDocumentListener extends DocumentListener {
    void update(DocumentEvent e);

    @Override
    default void insertUpdate(DocumentEvent e) {
        update(e);
    }
    @Override
    default void removeUpdate(DocumentEvent e) {
        update(e);
    }
    @Override
    default void changedUpdate(DocumentEvent e) {
        update(e);
    }
}

and then use it on your jTextField:

jTextField.getDocument().addDocumentListener(new SimpleDocumentListener() {
    @Override
    public void update(DocumentEvent e) {
        // Your code here
    }
});

or you can even use it with lambda expression:

jTextField.getDocument().addDocumentListener((SimpleDocumentListener) e -> {
    // Your code here
});

Upvotes: 6

adrCoder
adrCoder

Reputation: 3275

Just add a listener to the textfield so that it tracks when the text changes

textfieldName.getDocument().addDocumentListener(new DocumentListener() {
    // implement the methods
});

Upvotes: 5

Related Questions