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) ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.