我有这个代码:
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
,那么只有
*在*t myVar 中会发生这种情况。即“in”突出显示,但“t”不突出!
编辑 功能:
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) {
}