Chapter 20. Formatted Text Fields

Swing provides extended functionality for text fields through the JFormattedTextField class introduced in SDK 1.4. A JFormattedTextField can display its value in a friendly (and locale-specific) way, enforce restrictions on its value, be used to edit non-String objects, and permit its value (or part of its value) to be incremented or decremented with the keyboard.

Figure 20-1 shows several JFormattedTextFields, but for the full effect you may wish to run the SimpleFTF program and play with it a bit. Most of the fields show locale-specific formatting. The Integer field puts delimiters between millions and thousands and between thousands and units. It changes its appearance (by dropping the delimiters) temporarily when it gains focus. An invalid value either adjusts to the closest valid value or reverts to the most recent valid value when a field loses focus, depending on the field. (For example, try changing the date to February 34.) Also, be sure to notice how elements of the Date field can be incremented and decremented with the up arrow and down arrow keys. (The L&F specifies keys for incrementing and decrementing, but existing L&Fs use the up arrow and down arrow. In addition, the Enter and Escape keys usually commit and cancel an edit, respectively.)

JFormattedTextFields in two different locales

Figure 20-1. JFormattedTextFields in two different locales

You might also notice some nonintuitive ...

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.