public static void setJTextPaneFont(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.
MutableAttributeSet attrs = jtp.getInputAttributes();
// Set the font color
StyleConstants.setForeground(attrs, c);
// 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, false);
}
上面这段代码的目的是在from和to之间的两个索引之间更改特定代码行的颜色。调用此函数后,中的文本和颜色JTextPane
会正确更新(特定行)。
但是,当我尝试JTextPane
用新文本刷新(通过清空jtextpane
和重新添加新文本)时,所有文本都会自动绘制为用调用时最后分配的颜色setJTextPaneFont
。
基本上,整个文档(新文档)将变成彩色的,而不必调用上面的函数,而不仅仅是带有几条彩色的线。因此,我怀疑JTextPane
某种程度上的属性已被修改。
所以问题是,我如何能够将其重置JTextPane
为默认属性?
试试这个
public void setJTextPaneFont(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();
// MutableAttributeSet attrs = jtp.getInputAttributes();
AttributeSet attrs = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
// Set the font color
//StyleConstants.setForeground(attrs, c);
// Retrieve the pane's document object
StyledDocument doc = jtp.getStyledDocument();
// System.out.println(doc.getLength());
// 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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句