how-to

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.

STEP 1

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() {
  }

  @Override
  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( Color.red );    
      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.

STEP 2

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

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

STEP 3

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

When yes, focus to next item is then enabled.

TIP

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()) {
    c.requestFocusInWindow();
    if (!c.hasFocus()) {
      return;
    }
  }  
    
  /* -- action */
    
  System.out.println( "Action" );
}