JTextPane and regex problem

I have JTextPane

one that contains a string of XML characters and I want to change the color of the XML opening tags; to do this, I use a regular expression to find opening tags and then set the character attribute of the corresponding text indices to the selected color. This can be seen in the following code:

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();
    }
}

      

However, the problem is that Matcher.start()

both StyledDocument.setCharacterAttributes()

appear to increments differently (seems to StyledDocument

ignore newlines), which causes colored text to expand.

enter image description here

The problem is not with the regex itself, as System.out.println(matcher.group());

the while loop shows the following correct output:

<ROOT
<TAG
<TAG
<TAG

      

Is there a way to force the increment Matcher.start()

and StyledDocument.setCharacterAttributes()

, or will I have to implement a new row count?

EDIT: As Shlagi suggested, replacing everything \r\n

with \n

works , however I am concerned that this makes the code a little confusing and difficult to maintain. Other suggestions are welcome!

+3


source to share


1 answer


I don't know why JTextPane is doing it wrong. It may be that the styledoku thinks that "\r\n"

it is only one symbol. Don't ask why.

On line change

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

      



to

String nLine = "\n";

      

it works. JTextPane is only required "\n"

for new line on each OS

+1


source







All Articles