Java Swing How to - Use InputVerifier to validate JTextField








Question

We would like to know how to use InputVerifier to validate JTextField.

Answer

//w  w w. j a va  2 s.co m


   
import java.awt.BorderLayout;
import java.awt.Container;

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();
    JTextField textField3 = 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);
    textField3.setInputVerifier(verifier);

    Container contentPane = frame.getContentPane();
    contentPane.add(textField1, BorderLayout.NORTH);
    contentPane.add(textField2, BorderLayout.CENTER);
    contentPane.add(textField3, BorderLayout.SOUTH);
    frame.setSize(300, 100);
    frame.setVisible(true);
  }
}