我有一种方法可以突出显示文本区域中某个单词的所有出现。是否有任何方法可以使用开始和结束偏移来仅突出显示该行中的单词。使用开始和结束偏移来突出显示JTextArea中特定行上的文本
我的当前代码。
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");
结果:
我尝试使用开始和结束偏移方法,但没有luck.I试图突出显示“在”只在第6行。任何帮助在此非常赞赏。
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(http://sscce.org/)。 - 不要忽略异常输出。 '} catch(BadLocationException e){0} {e.printStackTrace();}应该是'} catch(BadLocationException e){e.printStackTrace();} }' – 2013-03-17 06:08:44