Search code examples
javaswingjtextfield

I want to listen to changes in JtextField


I really do not want to listen to DocumentListener. It generates too many events for me. I am interested in listening only when the focus moves away from this specific JtextField. Adding ActionListener will generate an event only when return key is pressed. I would like to get it when the user moves away with a tab key or by moving the mouse away. Is this possible? Thanks and Regards


Solution

  • Use FocusListener. focusLost will help you when user moves to some other fields.

            JTextField jf = new JTextField();
            jf.addFocusListener(new FocusListener() {
    
                @Override
                public void focusLost(FocusEvent arg0) {
                    // here you can have your code when user moves out
                }
    
                @Override
                public void focusGained(FocusEvent arg0) {
                    // TODO Auto-generated method stub
    
                }
            } );