避免让Swing荧光笔溢出新添加的文字

时间:2017-12-05 23:14:49

标签: java swing

我正在JTextPane上实现一个简单的荧光笔。我希望它在我输入时突出显示特殊关键字,例如ifcase等。正如IDE那样。

我面临的问题是,当我检测到一个特殊的关键字刚刚写完并突出显示它(这确实很有效)时,我之后输入的所有内容也会突出显示。看看API,我认为情况并非如此。怎么避免这个?

以下是有问题的代码:

if (word.equals("if")) {                        
    textPane.getHighlighter().addHighlight(wordStartIdx, pos+1, highlightPainter);
    textPane.getHighlighter().addHighlight(pos+2, pos+2, noHightlighter); // tried this to see if it would help, but it doesn't change anything.. anything typed after the word "if" will still be hightlighted!
}

由于

1 个答案:

答案 0 :(得分:2)

您可以尝试使用属性:

,而不是使用荧光笔
SimpleAttributeSet green = new SimpleAttributeSet();
StyleConstants.setForeground(green, Color.GREEN);

//  Change attributes on some existing text

StyledDocument doc = textPane.getStyledDocument();
int offset = textPane.getCaretPosition(); // should be after the "f"
doc.setCharacterAttributes(offset-2, 2, green, false);