Am having a method that highlights all the occurrences of a word in a Text Area. Is there any way to use start and end offset to highlight the word only in that line.
My current codes.
public static void highlight(JTextComponent textComp, String pattern) {
try {
Highlighter hilite = textComp.getHighlighter();
javax.swing.text.Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = 0;
// Search for pattern
while ((pos = text.indexOf(pattern, pos)) >= 0) {
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, pos + pattern.length(), painter2);
pos += pattern.length();
}
} catch (BadLocationException e) {
}
}
This is called on a JButton action performed:
highlight(textArea_1, "in");
The result:
I tried using the Start and End Offset Method but with no luck.I tried to highlight "in" on line 6 only.Any Help on this much appreciated.
static int iline =6;
public static void highlight(JTextComponent textComp, String pattern) {
try {
Highlighter hilite = textComp.getHighlighter();
javax.swing.text.Document doc = textComp.getDocument();
int start =((JTextArea) textComp).getLineStartOffset(iline);
int end = ((JTextArea) textComp).getLineEndOffset(iline);
String text = doc.getText(start,end);
int pos = start;
// Search for pattern
while ((pos = text.indexOf(pattern, pos)) >= start) {
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, pos + pattern.length(), painter2);
pos += pattern.length();
}
} catch (BadLocationException e) {
}
}