Auto-Completing Text Fields #50
Chapter 7, Text
|
265
HACK
When you type a comma, a question mark, or lowercase letters, they are
ignored.
You can do smart things with this tool, but also really stupid things. Let’s
say you want to restrict input to the characters that will be in a North Amer-
ican phone number of the form 123-456-7890. You can set the pattern to
[0-9\-]*, which will allow the user to type in only numbers and the hyphen.
Now you’re feeling clever, but you don’t like the fact that this still allows
users to type patterns that aren’t phone numbers, like
1111111 or -1-1-1-1.
So, you set the pattern to an exact description of the phone number pattern:
[0-9]{3}-[0-9]{3}-[0-9]{4}
But now your users can’t enter anything! Why? Because although that regu-
lar expression does specify the phone number pattern, no substring of it will
ever match. This expression specifies exactly 12 characters, so when you
type the first one, there’s only one character—it doesn’t match the pattern,
so it’s rejected.
The moral of the story here is to be thoughtful. You might decide to wire up
a
FocusListener so you impose the regex pattern only when the user moves
off the field, and change the “delete everything” behavior to something a lit-
tle less forceful; for example, you could pop up a dialog telling the user that
her input isn’t in the right format. Just don’t be surprised when regular
expressions give you results that are logical, but sometimes unexpected.
H A C K
#50
Auto-Completing Text Fields Hack #50
Typing in a whole URL is a pain. When the user starts to type, complete his
text with previously entered options, and let the user select one instead of
typing the whole URL.
The auto-completing text field is instantly familiar from its use in browsers,
where it is probably most needed. Nobody wants to have to try to type—or
for that matter even remember—a huge URL to some page they’ve visited
before, particularly not something like those Amazon.com URLs with inex-
plicable 20-digit numbers and bunches of seemingly arbitrary characters. On
the other hand, not everything needs to be saved as a bookmark.
Figure 7-2. Filtering JTextField input with a regular expression

Get Swing Hacks 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.