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.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »