Chandu Chandu - 10 months ago 47
Java Question

How to validate a JTextField?

How to validate a textfield to enter only 4 digits after the decimal point in Swing?

Answer Source

Any validation in Swing can be performed using an InputVerifier.

1. First create your own input verifier:

public class MyInputVerifier extends InputVerifier {
    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.