Check input with InputVerifier for JTextField in Java

Description

The following code shows how to check input with InputVerifier for JTextField.

Example


import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
/*  w  w w .  j av a  2 s  . c  om*/
public class Main {
  public static void main(String[] args) {
    JTextField tf = new JTextField();
    tf.setInputVerifier(new MyInputVerifier());

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new java.awt.GridLayout(0, 1));

    frame.add(tf);
    frame.setSize(150, 150);
    frame.setVisible(true);
    tf.requestFocus();
  }
}
class MyInputVerifier extends InputVerifier {
  public boolean verify(JComponent input) {
    JTextField tf = (JTextField) input;
    String pass = tf.getText();
    return pass.equals("A");
  }
}

The code above generates the following result.

Check input with InputVerifier 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