260
|
Chapter 7, Text
#48 Make Text Components Searchable
HACK
The continueSearch( ) method just calls find( ) on the matcher, if it exists. If
find( ) returns true, meaning it found a match somewhere, it sets the selec-
tion. Selections are defined by a caret with a dot. The dot represents the
selection point. By setting the dot at the start of the match and then moving
it with the
moveDot( )
function, it will create a selection between the start
and ending points. Finally,
setSelectionVisible(true)
scrolls the target
component, if needed, to make the selection visible on screen.
The action listener implementation will call
continueSearch( ) whenever an
action is performed. Both
JButton
s and
JTextField
s produce actions—the
former when they are clicked, and the latter when the user hits the Return
key. Listening for action events is an easy way of providing a hook to repeat
the search:
/* ActionListener implementation */
public void actionPerformed(ActionEvent evt) {
continueSearch( );
}
Since the matcher object remembers its place, each time find is called it will
continue searching from the current location. This means the user can just
hit Enter over and over to loop through the results in the document, high-
lighting each one as it goes along.
Adding Search to Swing Components
The following code creates a typical search interface. There is a large
JTextArea below a text field. The IncrementalSearch is attached to the text
area through its constructor. The search field is connected via the document
and action listeners. Once the class is put all together, it will look like
Figure 7-1.
Figure 7-1. Incremental repeatable search of a JTextArea

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.