Java InputVerifier class

Description

Java InputVerifier class

import java.awt.FlowLayout;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main extends JFrame {

  public Main() {
    super("Handling Mouse Event");
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setLayout(new FlowLayout());

    JTextField areaCodeField = new JTextField(3);
    this.getContentPane().add(areaCodeField);
    this.getContentPane().add(new JTextField(10));
    // Create an area code JTextField

    // Set an input verifier to the area code field
    areaCodeField.setInputVerifier(new InputVerifier() {
      @Override//from   w ww  .j  ava 2s  .c o m
      public boolean verify(JComponent input) {
        System.out.println("validate");
        String areaCode = areaCodeField.getText();
        if (areaCode.length() == 0) {
          return true;
        } else if (areaCode.length() != 3) {
          return false;
        }

        try {
          Integer.parseInt(areaCode);
          return true;
        } catch (NumberFormatException e) {
          return false;
        }
      }
    });
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}



PreviousNext

Related