Skip to Main Content
Java Swing, 2nd Edition
book

Java Swing, 2nd Edition

by Dave Wood, Robert Eckstein, Marc Loy, James Elliott, Brian Cole
November 2002
Intermediate to advanced content levelIntermediate to advanced
1278 pages
38h 26m
English
O'Reilly Media, Inc.
Content preview from Java Swing, 2nd Edition

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) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Threads, 3rd Edition

Java Threads, 3rd Edition

Scott Oaks, Henry Wong

Publisher Resources

ISBN: 0596004087Errata PageSupplemental Content