如何将JTextPane中的彩色文本重新显示回其默认颜色?

时间:2014-08-12 06:23:25

标签: java swing rgb jtextpane text-coloring

public void setJTextPane(JTextPane jtp, Color c, int from, int to) {
    // Start with the current input attributes for the JTextPane. This
    // should ensure that we do not wipe out any existing attributes
    // (such as alignment or other paragraph attributes) currently
    // set on the text area.

    StyleContext sc = StyleContext.getDefaultStyleContext();

    AttributeSet attrs = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
    // Set the font color

    // Retrieve the pane's document object
    StyledDocument doc = jtp.getStyledDocument();

    // Replace the style for the entire document. We exceed the length
    // of the document by 1 so that text entered at the end of the
    // document uses the attributes.
    doc.setCharacterAttributes(from, to, attrs, true);
}

public void recoverTextPane(JTextPane jtp, int from, int to) {
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet attrs = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, 
            new Color(51,51,51));
    StyledDocument doc = jtp.getStyledDocument();
    doc.setCharacterAttributes(from, to, attrs, true);
}

setJTextPane的目的是在两个索引之间绘制特定的JTextPane行。该功能按预期正常工作。但是,我想将该特定文本行转换回原始颜色。所以我基本上创建了一个单独的函数,将该行转换为已知的RGB。但是,这对文本没有任何作用。任何人都可以用代码诊断问题吗?

感谢您的帮助!!

1 个答案:

答案 0 :(得分:1)

SimplaAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setForeground(attrs, theColor);
StyledDocument doc = jtp.getStyledDocument();
doc.setCharacterAttributes(from, to, attrs, false);

您可以创建空属性集,指定前景色并应用它而不替换原始属性。检查fromto参数以覆盖正确的片段。