我有一种方法可以突出显示文本区域中所有出现的单词。有没有办法使用开始和结束偏移来突出显示该行中的单词。
我目前的代码。
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) {
}
}
这在执行的 JButton 操作上调用:
highlight(textArea_1, "in");
结果:
我尝试使用开始和结束偏移方法,但没有运气。我试图仅在第 6 行突出显示“in”。非常感谢任何帮助。
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) {
}
}