O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Handling Numerics

To a certain extent, JFormattedTextField treats the types Float, Double, Integer, Long, Short, and Byte (all subclasses of java.lang.Number) as interchangeable. This can sometimes be surprising. For example, with this field:

JFormattedTextField ftf = new JFormattedTextField(new Integer(4));

you might expect to be able to retrieve the value like this:

int val = ((Integer)ftf.getValue( )).intValue( ); // Incorrect

This code is likely to throw a ClassCastException because ftf.getValue( ) might return one of the other numeric types if the user has edited the field.[5]

A safer way to retrieve the value is:

int val = ((Number)ftf.getValue( )).intValue( ); // Correct

Casting to Number like this always works because the methods floatValue( ), doubleValue( ), integerValue( ), longValue( ), shortValue( ), and byteValue( ) are all defined in the java.lang.Number class.

If for some reason you want to force getValue( ) to return a specific numeric type, this can be done by instantiating a NumberFormat, calling its setValueClass( ) method, and passing the NumberFormat into the JFormattedTextField constructor.

The JFormattedTextField.AbstractFormatter Class

AbstractFormatter is an abstract inner class of JFormattedTextField that defines the basic API for formatters. Usually, there is no reason to extend AbstractFormatter directly since DefaultFormatter (discussed in the next section) provides a more complete starting point.

Public methods

public abstract Object stringToValue(String text) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required