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

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

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