Search code examples
javaswingjtextpanetext-coloringandroid-textattributes

Swing GUI appending colored text in JTextPane


public static void setJTextPaneFont(JTextPane jtp, Color c, int from, int to) {
    // Start with the current input attributes for the JTextPane. This
    // should ensure that we do not wipe out any existing attributes
    // (such as alignment or other paragraph attributes) currently
    // set on the text area.
    MutableAttributeSet attrs = jtp.getInputAttributes();

    // Set the font color
    StyleConstants.setForeground(attrs, c);

    // Retrieve the pane's document object
    StyledDocument doc = jtp.getStyledDocument();

    // Replace the style for the entire document. We exceed the length
    // of the document by 1 so that text entered at the end of the
    // document uses the attributes.
    doc.setCharacterAttributes(from, to, attrs, false);
}

The purpose of the above piece of code is to change the color of a particular line of code between two indices, from and to. After the call to this function, the text and color in JTextPane gets updated correctly(a particular line).

enter image description here

However, when I try to refresh the JTextPane with new texts(by emptying the jtextpane and re-appending new text), all text automatically gets painted into the color last assigned when called with setJTextPaneFont.

enter image description here

Basically, instead of just having a few colored lines, the whole document(new one) becomes colored without ever making a call to the function above. Therefore I suspect that the attributes of JTextPane somehow got modified.

So the question is, how would I be able to reset the JTextPane back to default attributes?


Solution

  • Try this one

    public void setJTextPaneFont(JTextPane jtp, Color c, int from, int to) {
                // Start with the current input attributes for the JTextPane. This
                // should ensure that we do not wipe out any existing attributes
                // (such as alignment or other paragraph attributes) currently
                // set on the text area.
    
                StyleContext sc = StyleContext.getDefaultStyleContext();
    
              // MutableAttributeSet attrs = jtp.getInputAttributes();
    
                AttributeSet attrs = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
                // Set the font color
                //StyleConstants.setForeground(attrs, c);
    
                // Retrieve the pane's document object
                StyledDocument doc = jtp.getStyledDocument();
                // System.out.println(doc.getLength());
    
                // Replace the style for the entire document. We exceed the length
                // of the document by 1 so that text entered at the end of the
                // document uses the attributes.
                doc.setCharacterAttributes(from, to, attrs, true);
            }