Java Change Color of Element on JTextPane using StyledDocument

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-16 06:04:09

问题


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 ;)


回答1:


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.




回答2:


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 :-)



来源:https://stackoverflow.com/questions/9745792/java-change-color-of-element-on-jtextpane-using-styleddocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!