Validate a value on the lostFocus event for JTextField in Java

Description

The following code shows how to validate a value on the lostFocus event for JTextField.

Example


//from  w ww.jav a 2  s .  c o m
import java.awt.FlowLayout;
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[] args) {
    JFrame f = new JFrame("Text Field Elements");

    final JTextField tf1 = new JTextField(5);
    f.setLayout(new FlowLayout());
    f.add(tf1);
    f.add(new JTextField(5));
    f.pack();
    f.setVisible(true);

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

The code above generates the following result.

Validate a value on the lostFocus event for JTextField in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer