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

Make Text Components Searchable #48
Chapter 7, Text
|
259
HACK
nothing tricky here. The complexity lies in the runNewSearch( ) function,
which handles the actual searching.
Running the Search
The runNewSearch( ) method pulls out the query string from the document.
Notice that it passes
0 and the length of the document into the getText( )
method. All of the Document methods operate in terms of a starting and end-
ing index. You deal with chunks of text only with these indices rather than
getting and setting
Strings, which would entail lots of byte copying. Copy-
ing isn’t a big deal for this hack, but it could be a problem for large docu-
ments (think several hundred kilobytes). Here is the
runNewSearch( )
method:
protected Matcher matcher;
private void runNewSearch(Document query_doc) {
try {
String query = query_doc.getText(0,query_doc.getLength( ));
Pattern pattern = Pattern.compile(query);
Document content_doc = content.getDocument( );
String body = content_doc.getText(0,content_doc.getLength( ));
matcher = pattern.matcher(body);
continueSearch( );
} catch (Exception ex) {
p("exception: " + ex);
ex.printStackTrace( );
}
}
After getting the text, runNewSearch( ) creates a new pattern from the query
(which requires no modification since it is a simple search), and then
retrieves the target document and text. With the search text, target body
text, and pattern in hand, it creates a
Matcher and calls continueSearch( ).
The
Matcher is the class that will do the actual searching with an internally
compiled regex:
private void continueSearch( ) {
if(matcher != null) {
if(matcher.find( )) {
content.getCaret().setDot(matcher.start( ));
content.getCaret().moveDot(matcher.end( ));
content.getCaret( ).setSelectionVisible(true);
}
}
}

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