Adding richtext to JTextPane using StyledDocument.insertString does not save fonts

I do not know if what I am trying to do is possible or not.

I have a console where I want to add formatted text declared as follows:

private final JTextPane statusText = new JTextPane();

I received a link to his document as follows:

private StyledDocument statusDocument = statusText.getStyledDocument();

I have defined several attributes:

private final SimpleAttributeSet gray;
private final SimpleAttributeSet black;
private final SimpleAttributeSet red;

and helper method:

private void appendStatusText(String text, SimpleAttributeSet attribute) {
        final String finalText = text;
        final SimpleAttributeSet finalAttribute = attribute;
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    statusDocument.insertString(statusDocument.getLength(), finalText, finalAttribute);
                } catch (BadLocationException e) {
                    log.error("Cannot add " + finalText, e);
                }
            }
        });
    }

I want to use appendStatusText with one of the attributes (gray, red, black) and some text, but everything that it shows is gray, I expect multicolor.

You can help.

PS: I got the code from the question here

+3
source share
2 answers

initDocument() TextComponentDemo . example .

+4

SimpleAttributeSet, :

private SimpleAttributeSet red = new SimpleAttributeSet();      
red.addAttribute(StyleConstants.CharacterConstants.Foreground, Color.red);
0

All Articles