Reputation: 14687
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
Upvotes: 3
Views: 2046
Reputation: 13397
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);
Upvotes: 0
Reputation: 205785
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.
Upvotes: 4