How can I validate a JTextField/JTextArea by adding listeners?

John Zukowski

Use the InputVerifier class introduced with the 1.3 release, or look at how to validate input with earlier Swing releases by creating a custom Document.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class VerifierSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Verifier Sample");
    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 {
          returnValue = true;
        } catch (NumberFormatException e) {
          returnValue = false;
        return returnValue;


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