Validating a JTextField When Permanently Losing the Focus
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; } } } }