【发布时间】:2013-03-05 16:20:17
【问题描述】:
我有一种方法可以突出显示文本区域中出现的所有单词。有没有办法使用开始和结束偏移来突出显示该行中的单词。
我当前的代码。
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) {
}
}
【问题讨论】:
-
如需尽快获得更好的帮助,请发布SSCCE。 -- 不要忽略异常输出。
} catch (BadLocationException e) { }应该是} catch (BadLocationException e) { e.printStackTrace(); }
标签: java jtextarea swing-highlighter