Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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
                    }
             }
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top