3

我有一个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 确实有效,但是我担心这会使代码有点混乱且难以维护。欢迎其他建议!

4

1 回答 1

1

I do not know why the JTextPane do it wrong. It could be, that in the styledocument think, that "\r\n" is only one character. Do not asked why.

When you change the line

String nLine = java.lang.System.getProperty("line.separator"); 

to

String nLine = "\n";

it works. JTextPane only need a "\n" for a newline on every OS

于 2014-09-17T13:05:43.807 回答