258
|
Chapter 7, Text
#48 Make Text Components Searchable
HACK
different date formats. This hack has much more humble needs, but Java 1.4’s
built-in regex support will make the search implementation very easy.
The plan for this hack is to create a searching utility object that targets a
JTextComponent
(the common subclass for all Swing text components such as
JTextArea
and
JTextField
). It will also listen for action and document
change events from a search component (usually a
JTextField
) to do the
actual searching. By constructing it with class agnostic listeners, you can
add it easily to existing programs without changing much code.
A Basic Search Class
The code in Example 7-1 defines the
IncrementalSearch
class, which imple-
ments the
DocumentListener and ActionListener interfaces. Programs with
search usually have a search field above the search target. The
IncrementalSearch constructor accepts a JTextComponent as the target, and
the document listener events will provide access to the search field itself. In
addition to the usual suspects, you’ll need to import the Swing event, Swing
text, and regex classes.
You can see that all three document listener methods just call
runNewSearch( ),
passing in the document. This forces the search to start over if the user types
new text, hits the Backspace key, or replaces a selection. So far, there is
Example 7-1. Starting the basic incremental search class
import javax.swing.event.*;
import javax.swing.text.*;
import java.util.regex.*;
public class IncrementalSearch
implements DocumentListener, ActionListener {
protected JTextComponent content;
public IncrementalSearch(JTextComponent comp) {
this.content = comp;
}
/* DocumentListener implementation */
public void insertUpdate(DocumentEvent evt) {
runNewSearch(evt.getDocument( ));
}
public void removeUpdate(DocumentEvent evt) {
runNewSearch(evt.getDocument( ));
}
public void changedUpdate(DocumentEvent evt) {
runNewSearch(evt.getDocument( ));
}

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.