
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