Download the
WordSearch.ziparchive.
For expediency you can install the project from existing
sources, but it is recommended to go through the step-by-step
construction.
Search and highlight in a JTextArea
When we search for a keyword in a text, it can either be considered
as "standalone" word, or part of a larger word. In this example
we will consider the former situation, i.e., that our keyword should not
be part of a larger "word". As is common in keyword searches,
we also want the search to be case-insensitive.
The Java regular expression match setup is as follows:
String keyword = // the keyword, assume only alphanumeric characters
String text = // the target text, possibly containing keywords
String patternStr = "\\b" + keyword + "\\b";
Pattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
int start = matcher.start(), end = matcher.end();
}
The word-boundary "\b" anchors mean that
if there is an adjacent character, that it is not a "word" character,
thus creating a pattern that identifies a standalone keyword.
The start and end positions
of the matching substring (which is an occurrence
of the keyword) can be used then to highlight the text in a
JTextArea (or other Swing text components).
The class java.swing.text.Highlighter
is used to create a highlight effect around a portion of the
textarea content.
Assuming that the variable ta
is the JTextArea which holds the text,
then we would use this code to create the desired effect:
Highlighter.HighlightPainter myPainter
= new DefaultHighlighter.DefaultHighlightPainter( Color.yellow );
ta.getHighlighter().addHighlight(start, end, myPainter);
Construction
Create the new Java Application project WordSearch.
Create a JFrame Form as the class views.Frame.
Set the layout of Frame to be BorderLayout.
Edit the Properties of the Frame,
making it have Minimum Size [450,450].
Drag a Menu Bar onto the Frame. Delete the Edit menu.
Drag a Menu Item onto the File menu.
Make the text of the menu item be "Open" and make the variable name be open.
Drag a Text Area into the Frame (the center).
Set the variable name of the Text Area to be display.
Drag a Panel into the bottom part.
Drag a Text Field and then a Button onto the Panel (anywhere).
Set the layout of the Panel to be FlowLayout.
Set the variable name of the Text Field to be keyfield.
Edit the Properties of display,
making it not editable, with linewrap checked.
Edit the Properties of keyfield,
making it have 15 columns
Make the Button have text "Search" and make the variable name be search.