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
并重新附加新文本),所有文本会自动绘制为使用{调用时最后分配的颜色{1}}。
基本上,不是只有几条彩色线条,整个文档(新文档)就会变成彩色而不会调用上面的函数。因此,我怀疑setJTextPaneFont
的属性以某种方式得到了修改。
所以问题是,我怎样才能将JTextPane
重置为默认属性?
答案 0 :(得分:3)
清空jtextpane并重新附加新文本问题可以通过多种方式解决:
致电doc.setCharacterAttributes(0, 1, attrs, true);
并在此处传递一个空的AttributeSet
重新创建文档,而不是doc.remove()/insert()
致电jtp.setDocument(jtp.getEditorKit().createDefaultDocument())
清除输入属性。添加插入符侦听器并检查文档是否为空。如果它为空,则删除所有所需的属性。
答案 1 :(得分:1)
试试这个
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);
}