Window (swing) applications

How to use InputVerifier class

With your`s own java.util.InputVerifier class you can ensure that the input field`s value for selected input item is valid. Your verification method is called when you leave the input item.


First, you need create your own java.util.InputVerifier descendant. In this descendant override verify() method. When this method returns false, the focus to next item is disabled.

package javatest1;

import java.awt.Color;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.UIManager;

class Verifier extends InputVerifier {

  public Verifier() {

  public boolean verify(JComponent input) {
    JTextField textField = (JTextField) input;               

    /* test, if starts with "a" or "A" */
    if ( textField.getText().toLowerCase().startsWith("a") ) {
      input.setBackground( UIManager.getColor( "TextField.background" ) );    
      return true;
    else {
      input.setBackground( );    
      return false;      

This class suppose input parameter in verify() method as JTextField class type. This field is then checked for "A" or "a" as a started value. In this case is returned true, in other situation false.


Now create dialog with one or more JTextField. For first JTextField set your InputVerifier.

InputVerifier verifier = new Verifier();
this.jTextField1.setInputVerifier( verifier );


When your item doesn`t contains specified value, focus the next item is disabled.

When yes, focus to next item is then enabled.


A little problem is a mouse click on the button to doing some action. In this situation you must call this verify check explicitly (JDK 1.6):

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

  /* -- used for calling the InputVerifier */
  JComponent c = (JComponent) evt.getSource();
  if (c.getVerifyInputWhenFocusTarget()) {
    if (!c.hasFocus()) {
  /* -- action */
  System.out.println( "Action" );