O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Force Text Input into Specific Formats #49
Chapter 7, Text
|
261
HACK
public static void main(String[] args) {
JTextArea text_area = new JTextArea(10,20);
JScrollPane scroll = new JScrollPane(text_area);
IncrementalSearch isearch = new IncrementalSearch(text_area);
JTextField search_field = new JTextField( );
search_field.getDocument( ).addDocumentListener(isearch);
search_field.addActionListener(isearch);
JFrame frame = new JFrame("Incremental Search Hack");
frame.getContentPane( ).add("North",search_field);
frame.getContentPane( ).add("Center",scroll);
frame.pack( );
frame.show( );
}
As the user types, the search selection will update on every keystroke.
Return (or Enter) will jump to the next result, and Backspace will make the
search less specific.
Hacking the Hack
You could expand this hack with support for case-insensitive searching, or
allow users to type in more complicated regular expressions instead of
straight text-matching. Because the component is built as an event listener,
it’s very easy to drop your search routines into existing applications. Event
listeners are probably the best way to add new features, such as incremental
searching.
H A C K
#49
Force Text Input into Specific Formats Hack #49
Use Java’s powerful pattern matching to enforce rules on typed input
Validating input is an important GUI task, and some applications will vali-
date your input when you tab off a field or even validate it on every key-
stroke. After all, it’s a lot easier to deal with bogus data by not letting it into
your system in the first place.
One technique for validating user input is to use a regular expression and
then evaluate the input against it. For example, a field that can be uppercase
letters only must always match the expression
[A-Z]*, and one that can be
any combination of uppercase, lowercase, numbers, and spaces must match
[A-Za-z0-9 ]* (notice the space after 9).
Java’s regex feature lets you create
TextComponents that enforce matching
against an expression. The basic idea is to watch for changes in the under-
lying
Document and do your pattern match then.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required