我有这个代码:
JTextArea textComp;
Highlighter hilite = textComp.getHighlighter();
if (word.toString().equals(pattern[i]))
{
hilite.addHighlight(posStart, (posEnd), myHighlighter);
break;
}
word
是一个 StringBuilder
假设 if
中的条件匹配并且 hilite.addHighlight(posStart, (posEnd), myHighlighter);
- 该语句将被执行。
然后 textComp
包含
int myVar
我尝试像这样突出显示
int myVar
当时,posStart = 0
和 posEnd = 3
。但是当我在 textArea
中输入一些内容时,荧光笔会像这样延伸到末尾:
int myVar
谁能帮我解决这个问题吗?
如果我发表声明:
hilite.addHighlight(posStart, (posEnd-1), myHighlighter);
然后使用posStart=0, posEnd=3
,然后仅
*in*t myVar this happens. i.e "in" is highlighted but "t" is not!
编辑 功能:
Highlighter.HighlightPainter myHighlighter = new MyHighlightPainter(
Color.LIGHT_GRAY);
try {
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
String[] words = text.split(" ");
int posEnd, posStart = 0;
while (text.length() > posStart) {
posEnd = posStart;
StringBuilder word = new StringBuilder();
while (posEnd < text.length() && text.charAt(posEnd) != ' ') {
word.append(text.charAt(posEnd++));
}
for (int i = 0; i < pattern.length; i++) {
if (word.toString().equals(pattern[i])) {
hilite.addHighlight(posStart, (posEnd-1), myHighlighter);
break;
}
}
posStart = posStart + posEnd + 1;
}
} catch (BadLocationException e) {
}
最佳答案
actually I was wondering how this Highlighter works!
是的,API 令人困惑。我相信第一个索引是包容性的,最后一个索引是排除性的。
每当我在搜索单词时突出显示时,我都会使用如下代码:
String text = "one two three four...";
String search "three";
int offset = text.indexOf(search);
if (offset != -1)
textPane.getHighlighter().addHighlight(offset, offset + search.length(), painter);
关于java - Java Swing 的荧光笔如何在边缘情况下工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17087167/