3

I have got a JTextField and I want to add listener to it, which will receive some event as soon as the JTextField looses focus (say when I press with mouse to another component). Also I want a listener to receive an event when the text parameter of JTextField is changed (like when I set jtextfield.setText(anotherText)). Any idea how should I do it?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
lnk
  • 593
  • 2
  • 11
  • 27

2 Answers2

6

For the first one, you need a FocusListener. For the second one, you need to add a DocumentListener to the document of the text field.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
3

As @MadProgrammer point out, if you are only interested in listening text property. Just add a PropertyChangeListener.

Example:

   JTextField textfield = new JTextField();
   //for focus use FocusAdapter and just override focus lost
   textfield.addFocusListener(new FocusAdapter(){
       @Override
       public void focusLost(final FocusEvent evt){
           //i always like to wrap this method with swing utilities
           // which puts it at the end of the EventQueue, so it's executed after all pending events
           SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run(){
                    //code here
                }
           });
       } 
  });

  textfield.addPropertyChangeListener("text", new PropertyChangeListener(){
             @Override
             public void propertyChange(PropertyChangeEvent evt){
                    if(evt == null)
                        return;

                    if("text".equals(evt.getPropertyName())){
                         //code here
                    }
             }
  });
nachokk
  • 14,363
  • 4
  • 24
  • 53
  • 2
    FYI the property change listener doesn't work for me, using Java 1.6. It's never called. Javadoc for java.asw.Container.addPropertyChangeListener lists the properties and does not include "text". Perhaps it was added in a later version. – Jeff Learman Apr 27 '15 at 17:10
  • 1
    @JeffLearman,The "value" property might be the appropriate one to use. – Samuel Edwin Ward May 20 '15 at 20:28