这对我来说有点过头了..我正在使用JTextPane聊天,我在那里有颜色。我想要的是,通过引用一个元素来改变它的颜色。我正在使用StyledDocument,我不知道怎么做..
提前感谢;)
发布于 2012-03-17 14:07:04
使用setCharacterAttributes()。使用StyleConstants.setBackground()/setForeground().在SimpleAttributeSet中定义所需的颜色使用元素的起点和终点偏移量作为偏移量和长度。
如果最后一个属性为false,则只替换SimpleAttributeSet中定义的元素的塔式属性。
发布于 2012-03-17 18:01:55
你想要的似乎可以用一种方法来描述,看看吧:
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);
}只需尝试将您的JTextPane的引用与您的String和您想要提供的相应Colour一起传递给此方法,就会看到魔力:-)
https://stackoverflow.com/questions/9745792
复制相似问题