Value Change Listener to JTextField

前端 未结 12 2101
情歌与酒
情歌与酒 2020-11-22 04:16

I want the message box to appear immediately after the user changes the value in the textfield. Currently, I need to hit the enter key to get the message box to pop out. Is

12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 04:28

    Just create an interface that extends DocumentListener and implements 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:

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

    or you can even use lambda expression:

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

提交回复
热议问题