Mega Code Archive

 
Categories / Java Tutorial / Swing Event
 

Validate a value on the lostFocus event

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();   } }