tags:

views:

114

answers:

1

Hi all,

how to validate a textfield to enter only 4 digits after the decimal point in Swing.

Regards,

Chandu

+7  A: 

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.

DR
Use `BigDecimal` instead and then check the number of decimals with `scale()`.
Aaron Digulla
Thanks, I've updated the code.
DR
Chandu