我有一个JTextPane
包含 XML 字符的字符串,我希望更改 XML 开始标签的颜色;为此,我使用正则表达式查找开始标签,然后将相关文本索引的字符属性设置为所选颜色。这可以在以下代码中看到:
import java.awt.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.text.*;
public class Test {
String nLine = java.lang.System.getProperty("line.separator");
String xmlString = "<ROOT>" + nLine + " <TAG>Tag Content</TAG>" + nLine + " <TAG>Tag Content</TAG>" + nLine + " <TAG>Tag Content</TAG>" + nLine + "</ROOT>";
public Test(){
JTextPane XMLTextPane = new XMLTextPane();
JScrollPane pane = new JScrollPane(XMLTextPane);
pane.setPreferredSize(new Dimension(500,100));
JOptionPane.showConfirmDialog(null, pane);
}
class XMLTextPane extends JTextPane{
public XMLTextPane(){
super.setText(xmlString);
StyleContext context = new StyleContext();
Style openTagStyle = context.addStyle("Open Tag", null);
openTagStyle.addAttribute(StyleConstants.Foreground, Color.BLUE);
StyledDocument sdocument = this.getStyledDocument();
Pattern pattern = Pattern.compile("<([a-z]|[A-Z])+");
Matcher matcher = pattern.matcher(super.getText());
while (matcher.find()) {
sdocument.setCharacterAttributes(matcher.start(), matcher.group().length() , openTagStyle, true);
}
}
}
public static void main(String[] args){
new Test();
}
}
然而,问题是Matcher.start()
并且StyledDocument.setCharacterAttributes()
似乎以不同的方式递增(似乎StyledDocument
忽略了换行符),从而导致彩色文本交错。
问题不在于正则表达式本身,因为System.out.println(matcher.group());
while 循环中的 a 显示以下正确输出:
<ROOT
<TAG
<TAG
<TAG
有没有办法强制Matcher.start()
和StyledDocument.setCharacterAttributes()
持续增加,或者我必须实现一个新的行计数器?
编辑:正如 Schlagi 建议的那样,将所有替换\r\n
为\n
确实有效,但是我担心这会使代码有点混乱且难以维护。欢迎其他建议!