Java JComponent grab focus
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) { }/*w w w. java 2s . com*/ 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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(textField, BorderLayout.NORTH); frame.add(new JTextField(), BorderLayout.SOUTH); 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(); } }