简体   繁体   中英

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!

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM