TiagoM
TiagoM

Reputation: 187

Java Change Color of Element on JTextPane using StyledDocument

this is kinda overkill for me.. I am using a JTextPane for a chat, I have colors there.. What I want is, with reference to a element changing the color of it.. I am using StyledDocument, I have no clue how to do this..

Thanks in advance ;)

Upvotes: 1

Views: 3231

Answers (2)

nIcE cOw
nIcE cOw

Reputation: 24616

Seems like what you asking for can be described in a single method, have a look :

private void appendToPane(JTextPane tp, String msg, Color c)
{
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

    aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
    aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

    int len = tp.getDocument().getLength();
    tp.setCaretPosition(len);
    tp.setCharacterAttributes(aset, false);
    tp.replaceSelection(msg);
}

Just try to pass the reference of your JTextPane along with your String and respective Colour that you want to provide, to this method and see the magic :-)

Upvotes: 2

StanislavL
StanislavL

Reputation: 57381

Use setCharacterAttributes(). Define desired color in a SimpleAttributeSet using StyleConstants.setBackground()/setForeground(). Use Element's start and end offsets for the offset and length.

If the last attribute is false only thouse attributes of Element which are defined in the SimpleAttributeSet are replaced.

Upvotes: 3

Related Questions