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。但是,这对文本没有任何作用。任何人都可以用代码诊断问题吗?
感谢您的帮助!!
答案 0 :(得分:1)
SimplaAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setForeground(attrs, theColor);
StyledDocument doc = jtp.getStyledDocument();
doc.setCharacterAttributes(from, to, attrs, false);
您可以创建空属性集,指定前景色并应用它而不替换原始属性。检查from
和to
参数以覆盖正确的片段。