我有一个JTextPane
,其中包含一串XML字符,并且我希望更改XML开头标签的颜色;为此,我使用正则表达式查找开始标签,然后将相关文本索引的character属性设置为所选颜色。可以在以下代码中看到:
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
忽略换行符),从而导致彩色文本错开。问题不在于正则表达式本身,因为while循环中的
System.out.println(matcher.group());
显示以下正确输出:<ROOT
<TAG
<TAG
<TAG
有没有办法强制
Matcher.start()
和StyledDocument.setCharacterAttributes()
一致地增加,还是我必须实现一个新的行计数器?编辑:正如Schlagi所建议的,用
\r\n
替换所有\n
可以完成的工作,但是我担心这会使代码有些混乱并且难以维护。欢迎其他建议! 最佳答案
我不知道为什么JTextPane做错了。在styledocument中认为"\r\n"
可能只是一个字符。不问为什么。
换线时
String nLine = java.lang.System.getProperty("line.separator");
至
String nLine = "\n";
有用。
JTextPane在每个OS上只需要
"\n"
作为换行符