How to validate a JTextField?

Any validation in Swing can be performed using an InputVerifier.

1. First create your own input verifier:

public class MyInputVerifier extends InputVerifier {
    @Override
    public boolean verify(JComponent input) {
        String text = ((JTextField) input).getText();
        try {
            BigDecimal value = new BigDecimal(text);
            return (value.scale() <= Math.abs(4)); 
        } catch (NumberFormatException e) {
            return false;
        }
    }
}

2. Then assign an instance of that class to your text field. (In fact any JComponent can be verified)

myTextField.setInputVerifier(new MyInputVerifier());

Of course you can also use an anonymous inner class, but if the validator is to be used on other components, too, a normal class is better.

Also have a look at the SDK documentation: JComponent#setInputVerifier.

Leave a Comment