gpt4 book ai didi

java - Java Swing 的荧光笔如何在边缘情况下工作?

转载 作者:行者123 更新时间:2023-12-01 14:27:34 25 4
gpt4 key购买 nike

我有这个代码:

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 = 0posEnd = 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com