我想为所有与赞美匹配的单词着色
public WarnaText(JTextPane source) throws BadLocationException
{
source.setForeground(Color.BLACK);
Matcher komen=Pattern.compile("//.+").matcher(source.getText());
while(komen.find())
{
String getkomen=komen.group();
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Concolas");
int start = source.getText().indexOf(getkomen);
source.select(start,start + getkomen.length());
source.setCharacterAttributes(aset, false);
}
}
但是,有些单词在包含许多注释的 JTextPane 上没有着色
您的代码检索注释文本 ( getkomen=komen.group()
),然后搜索该文本的第一个实例 ( ...indexOf(getkomen)
)。如果您有多个相同的注释,则只有第一个注释会被着色。
Matcher
将使用 start()
和 end()
为您提供找到的文本的位置。你应该只使用这些。
Matcher komen=Pattern.compile("//.+").matcher(source.getText());
while(komen.find())
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Concolas");
source.select(komen.start(), komen.end());
source.setCharacterAttributes(aset, false);
}
您可以从
source.select(start, start+getkomen.length)
更改为source.select(komen.start(),komen.end())
public WarnaText(JTextPane source) throws BadLocationException
{
source.setForeground(Color.BLACK);
Matcher komen=Pattern.compile("(/\*([^\*]|(\*(?!/))+)*+\*+/)|(\/\/.+)").matcher(source.getText());
while(komen.find())
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Concolas");
source.select(komen.start(),komen.end());
source.setCharacterAttributes(aset, false);
}
}