Java Swing How to - Validate a value on the lostFocus event with FocusListener








Question

We would like to know how to validate a value on the lostFocus event with FocusListener.

Answer

//from w w w .j  ava 2 s  . com
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

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

public class Main {
  JTextField tf1;
  public void init() {
    tf1 = new JTextField(5);
 
    tf1.addFocusListener(new FocusListener() {
      public void focusGained(FocusEvent e) {
      };
      public void focusLost(FocusEvent e) {
        if (!e.isTemporary()) {
          String content = tf1.getText();
          if (!content.equals("a") ) {
            System.out.println("illegal value! " + content);
            SwingUtilities.invokeLater(new FocusGrabber(tf1));
          }
        }
      }
    });
  }
}

class FocusGrabber implements Runnable {
  private JComponent component;

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

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