Validate a value on the lostFocus event : FocusListener « Swing Event « Java Tutorial






import java.awt.BorderLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Main {
  public static void main(String[] a) {
    final JTextField textField = new JTextField(5);
 
    textField.addFocusListener(new FocusListener() {
      public void focusGained(FocusEvent e) {
      }
      public void focusLost(FocusEvent e) {
        if (!e.isTemporary()) {
          String content = textField.getText();
          if (!content.equals("a") ) {
            System.out.println("illegal value! " + content);
            SwingUtilities.invokeLater(new FocusGrabber(textField));
          }
        }
      }
    });
    JFrame frame = new JFrame();
    frame.add(textField,BorderLayout.CENTER);
    frame.setSize(300,300);
    frame.setVisible(true);
  
  
  }
}

class FocusGrabber implements Runnable {
  private JComponent component;

  public FocusGrabber(JComponent component) {
    this.component = component;
  }

  public void run() {
    component.grabFocus();
  }
}








15.16.FocusListener
15.16.1.The FocusListener Interface: respond to a component gaining or losing the focus
15.16.2.The event IDs defined in the FocusEvent class
15.16.3.How to Write a Focus ListenerHow to Write a Focus Listener
15.16.4.FocusListener and FocusEvent
15.16.5.Validating a JTextField When Permanently Losing the Focus
15.16.6.Use Focus Events in Swing
15.16.7.Validate a value on the lostFocus event