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