Monthly Archives: February 2005

Java Swing Number Validatation

With the advent of Java 1.4, (ok so it happened a little while ago), came the handy class: JFormattedTextField which extends JTextField. You can read all about it in the Swing Tutorial.

In combination with the Matchers, this gives a powerful interface for limiting text to a specified form.

Unfortunately, there is not native support for a number input field that can be set to an arbitary inclusive range.

I produced this nice little hack that allows entry of a number between 0 and 1 inclusive, as required for probability.

        formatter = new MaskFormatter(“#.##”) {
            public Object stringToValue(String value) throws ParseException {

                Object o = super.stringToValue(value);
                if (Double.parseDouble(o.toString()) > 1.0) {
                    throw new ParseException(“greater than 1”, 0);
                return o;
        field = new JFormattedTextField(formatter);

So this reads as, create a formatter that matches a digit(#), a decimal point (.) then 2 more digits.

This formatter overrides the stringToValueMethod, delegating most of the work to the superclass, throwing an Exception if the number is bigger than 1.0

The formatter is then configured to use 0’s for fields that the user hasn’t entered anything into, and to update the model as soon as a valid entry is made.

It is then used by a JFormattedTextField, which has its contents exposed through its getValue() method.