The JFormattedTextField Class

JFormattedTextField extends JTextField primarily by having a value property in addition to its content (accessed by the text property). The user may manipulate the field’s content, but its value doesn’t (necessarily) change until the user commits the edit. If the user cancels the edit, the content reverts back to the most recent valid value.

The field’s value may be of any Object type, but it is displayed and edited as a String. The field uses its formatter to translate between Object and String representations.

JFormattedTextField works by maintaining an AbstractFormatterFactory (defined as a public abstract inner class). Whenever the field receives focus, it obtains an AbstractFormatter (another public abstract inner class) from the factory to oversee editing until it loses focus. It also queries the factory for a formatter at other times, such as when it loses focus or when setValue( ) is called.

The factory does not generally create new objects (as other factory classes typically do), but usually just hands out an appropriate existing formatter instance for the field to use. The factory is used to permit different formatters to be used for viewing versus editing, not to support a variety of different types. JFormattedTextField does support a variety of types, but its constructor creates a custom factory for the type passed in. So if you create a new JFormattedTextField(new java.util.Date( )), every formatter it gets from its factory is for dates, ...

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.