Java Reference
In-Depth Information
To try this out, you'll need to actually find a web page that uses H1, H2, or H3 tags. This
isn't easy these days. Alternatively, you can just switch the H1, H2, and H3 to different tags that
you know you will find.
JFormattedTextField Formats
In Chapter 15, you got a little taste of the JFormattedTextField component. Now, you'll get the
rest of the meal. A JFormattedTextField is used for accepting formatted input from a user. This
sounds simple, but is actually quite important and involved. Without a JFormattedTextField ,
getting formatted input isn't as easy as it sounds. Throwing in localization requirements makes
life really interesting.
Not only does the JFormattedTextField component support entering input in a formatted
fashion, but it also allows the user to use the keyboard to increment and decrement the input
value; for example, to scroll through the available months in a date.
For a JFormattedTextField , the validation magic is controlled by the focusLostBehavior
property. This can be set to one of four values:
COMMIT_OR_REVERT : This is the default. When the component loses focus, the component
automatically calls the commitEdit() method internally. This will parse the component's
contents and throw a ParseException on error, reverting the contents to the most recent
valid value.
COMMIT : This setting is similar to COMMIT_OR_REVERT , but it leaves the invalid contents
within the field, allowing the user to modify the setting.
REVERT : This setting always reverts the value.
PERSIST : This setting essentially does nothing. When the focusLostBehavior property is
set to PERSIST , you should manually call commitEdit() yourself to see if the contents are
valid before using the contents.
Dates and Numbers
For starters, let's see how to use the JFormattedTextField to accept input that should be inter-
nationalized. This includes all forms of dates, times, and numbers—basically, anything whose
format can be acquired from a DateFormat or NumberFormat object.
If you provide a Date object or Number subclass to the JFormattedTextField constructor, the
component passes the input String to the constructor of that object type to do the input validation.
Instead, you should work with the InternationalFormatter class in the java.swing.text
package by passing a DateFormat or NumberFormat into the constructor. This allows you to
specify long versus short form for dates and times, as well as currency, percentage, floats,
and integers for numbers.
Date and Time Formats
To demonstrate date and time formatting, the example in Listing 16-7 accepts various date and
time input. From top to bottom, the inputs are short date format for default locale, full date
format for United States English, medium date format for Italian, day of week in French, and
short time format for the default locale.
Search WWH ::




Custom Search