【问题标题】:Issue with JTextPane and regexJTextPane 和正则表达式的问题
【发布时间】:2014-09-17 12:47:42
【问题描述】:

我有一个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 忽略换行符),从而导致彩色文本错开。

问题不在于正则表达式本身,因为 while 循环中的 System.out.println(matcher.group()); 显示以下正确输出:

<ROOT
<TAG
<TAG
<TAG

有没有办法强制Matcher.start()StyledDocument.setCharacterAttributes() 持续递增,还是我必须实现一个新的行计数器?

编辑:正如 Schlagi 建议的那样,将所有 \r\n 替换为 \n 确实 工作,但我担心这会使代码有点混乱且难以维护。欢迎提出其他建议!

【问题讨论】:

    标签: java regex counter jtextpane styleddocument


    【解决方案1】:

    我不知道为什么 JTextPane 做错了。在 styledocument 中认为,"\r\n" 可能只是一个字符。不要问为什么。

    换行时

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

    String nLine = "\n";
    

    它有效。 JTextPane 只需要 "\n" 在每个操作系统上换行

    【讨论】:

    • 不幸的是,在实际应用程序中,输入 xml 使用 \r\n 作为行分隔符,因此这不起作用。
    • 解决方法是将所有"\r\n" 替换为"\n"
    • @schlagi123 替换所有 \r\n 确实有效,尽管我不禁觉得它有点“草率”。稍等一下,看看其他人是否有更好的建议,如果没有,请接受您的回答。
    猜你喜欢
    • 2011-12-31
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多