3

I don't know if what I'm trying to do is possible or not.

I have console where I want to append formatted text declared like this:

private final JTextPane statusText = new JTextPane();

I got a reference to its styled document like this:

private StyledDocument statusDocument = statusText.getStyledDocument();

I defined a few attributes :

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

and a 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 all it's showing is in gray, I'm expecting multicolors.

Can you help please.

PS: I got the code from the question here

Community
  • 1
  • 1
Charbel
  • 14,187
  • 12
  • 44
  • 66
  • maybe is/are there another issue(s), please edit you post with a [SSCCE](http://sscce.org/) – mKorbel Apr 17 '12 at 15:12
  • @mKorbel Ok, I'll try to prepare a SSCCE, but first, can you please confirm that it's ok to mix and match different SimpleAttributeSet instances with parts of the text added to a JTextPane? – Charbel Apr 17 '12 at 15:16
  • 1
    no I think that there isn't issue, another question isn't something, somehow un_clear from (@camickr's) describtion), you can [(pretty to) use one of those two codes for your SSCCE](http://stackoverflow.com/questions/9650992/how-to-change-text-color-in-the-jtextarea/9651404#9651404) – mKorbel Apr 17 '12 at 15:27
  • looks like the error is somewhere else, I used the SSCCE you suggested, and modified it, and now it behaves as i expect. I'll keep investigating, thanks – Charbel Apr 17 '12 at 16:48
  • the problem was that the text panel had setEnabled to false, which had the effect of everything appearing gray... – Charbel Apr 19 '12 at 09:51

2 Answers2

4

The initDocument() method of TextComponentDemo shows one approach to constructing such a document. The example appears among the Examples That Use Text Panes and Editor Panes in the tutorial article How to Use Editor Panes and Text Panes.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
0

You have to define your SimpleAttributeSet and then add the attributes you want, like so:

private SimpleAttributeSet red = new SimpleAttributeSet();      
red.addAttribute(StyleConstants.CharacterConstants.Foreground, Color.red);
james.garriss
  • 12,959
  • 7
  • 83
  • 96