
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 ...