The NumberFormatter Class

NumberFormatter is a subclass of InternationalFormatter that uses an object of type java.text.NumberFormat as its format. JFormattedTextField instantiates a NumberFormatter for itself if you pass a subclass of Number or a java.text.NumberFormat into its constructor. With a subclass of Number, the format is localized to the current locale. Again, this is usually what you want, but if you want your program to use the same number format no matter where in the world it is run, construct your JFormattedTextField with a specific java.text.NumberFormat.

Properties

NumberFormatter does not define any properties beyond those it inherits (see Table 20-6). The minimum and maximum properties can be handy if you want the field to be restricted to a specific range.

Constructors

public NumberFormatter( )

Create a new NumberFormatter and call java.text.NumberFormat.getNumberInstance( ) to set the format, which is a general-purpose format for the current locale.

public NumberFormatter(java.text.NumberFormat format)

Create a new NumberFormatter with the specified format.

Public Method

public Object stringToValue(String text) throws java.text.ParseException

NumberFormatter does not technically override this method, but (through private methods) does alter how it works slightly. This method should succeed if valueClass has been set to Integer, Long, Short, Byte, Float, or Double, even though those classes don’t have constructors that take a single String argument.

The JFormattedTextField.AbstractFormatterFactory ...

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.