Java使用StyledDocument更改JTextPane上元素的颜色

Java使用StyledDocument更改JTextPane上元素的颜色,java,swing,colors,styles,jtextpane,Java,Swing,Colors,Styles,Jtextpane,这对我来说有点过分了。。我正在使用JTextPane聊天,我有颜色。。我想要的是,关于改变颜色的元素。。 我正在使用StyledDocument,我不知道如何执行此操作 提前感谢;) 使用setCharacterAttributes()。使用StyleConstants.setBackground()/setForeground()在SimpleAttributeSet中定义所需的颜色。使用图元的起点偏移和终点偏移作为偏移和长度 如果最后一个属性为false,则仅替换SimpleAttribut

这对我来说有点过分了。。我正在使用JTextPane聊天,我有颜色。。我想要的是,关于改变颜色的元素。。 我正在使用StyledDocument,我不知道如何执行此操作

提前感谢;)

使用setCharacterAttributes()。使用StyleConstants.setBackground()/setForeground()在SimpleAttributeSet中定义所需的颜色。使用图元的起点偏移和终点偏移作为偏移和长度

如果最后一个属性为false,则仅替换SimpleAttributeSet中定义的元素的千个属性。

使用setCharacterAttributes()。使用StyleConstants.setBackground()/setForeground()在SimpleAttributeSet中定义所需的颜色。使用图元的起点偏移和终点偏移作为偏移和长度


如果最后一个属性为false,则仅替换SimpleAttributeSet中定义的元素的千个属性。

似乎您所要求的可以用单个方法描述,请查看:

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
引用以及您想要提供的
字符串
和相应的
颜色
传递给此方法,就可以看到神奇之处:-)

似乎您所要求的可以用一个方法来描述,看看:

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
的引用,连同你想要提供的
字符串和相应的
颜色,传递到这个方法,看看它的神奇之处:-)

谢谢,这是用来插入带有颜色的文本的,我知道,伙计。我看到的是在已经插入的文本上编辑颜色的东西,明白吗?斯坦尼斯拉夫已经帮了我;)感谢you@TiagoM:啊哈,似乎我误解了这个问题:(,我的错,很抱歉。@TiagoM:呵呵,欢迎你继续微笑:-)谢谢,这是插入带颜色的文本,我知道,伙计。我看到的是在已经插入的文本上编辑颜色的东西,明白吗?斯坦尼斯拉夫已经帮了我;)感谢you@TiagoM:啊哈,似乎我误解了这个问题:(,我的错,很抱歉。@TiagoM:呵呵,欢迎你继续微笑:-)