Verify Input During Focus Traversal in Java

Description

The following code shows how to verify Input During Focus Traversal.

Example


    /*from w ww  . j  a v  a2s .  c  o m*/
import java.awt.BorderLayout;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Verifier Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JTextField textField1 = new JTextField();
    JTextField textField2 = new JTextField();
    
    InputVerifier verifier = new InputVerifier() {
      public boolean verify(JComponent comp) {
        boolean returnValue;
        JTextField textField = (JTextField) comp;
        try {
          Integer.parseInt(textField.getText());
          returnValue = true;
        } catch (NumberFormatException e) {
          returnValue = false;
        }
        return returnValue;
      }
    };
    textField1.setInputVerifier(verifier);
    frame.add(textField1, BorderLayout.NORTH);
    frame.add(textField2, BorderLayout.CENTER);
    frame.setSize(300, 100);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Verify Input During Focus Traversal 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