Validating a JTextField When Permanently Losing the Focus : FocusListener « Swing Event « Java Tutorial






import java.awt.FlowLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;

public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField(10);
    JTextField component1 = new JTextField(10);
    component.addFocusListener(new MyFocusListener());
    component1.addFocusListener(new MyFocusListener());
    JFrame f = new JFrame();
    f.setLayout(new FlowLayout());
    f.add(component1);
    f.add(component);
    f.pack();
    f.setVisible(true);

  }
}
class MyFocusListener extends FocusAdapter {
  boolean showingDialog = false;

  public void focusGained(FocusEvent evt) {
    final JTextComponent c = (JTextComponent) evt.getSource();
    String s = c.getText();

    for (int i = 0; i < s.length(); i++) {
      if (!Character.isDigit(s.charAt(i))) {
        c.setSelectionStart(i);
        c.setSelectionEnd(i);
        break;
      }
    }
  }

  public void focusLost(FocusEvent evt) {
    final JTextComponent c = (JTextComponent) evt.getSource();
    String s = c.getText();

    if (evt.isTemporary()) {
      return;
    }
    for (int i = 0; i < s.length(); i++) {
      if (!Character.isDigit(s.charAt(i))) {
        System.out.println("must only contain digits");
        c.requestFocus();
        break;
      }
    }
  }
}








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