Reputation: 187
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
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
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