1
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);
}

上面这段代码的目的是改变两个索引之间的特定代码行的颜色,从和到。调用此函数后,文本和颜色JTextPane会正确更新(特定行)。

在此处输入图像描述

但是,当我尝试JTextPane使用新文本刷新 (通过清空jtextpane并重新附加新文本)时,所有文本都会自动绘制为使用 调用时最后分配的颜色setJTextPaneFont

在此处输入图像描述

基本上,不是只有几条彩色线条,而是整个文档(新的)在没有调用上面的函数的情况下变成彩色的。因此我怀疑JTextPane不知何故的属性被修改了。

所以问题是,我如何才能将其重置JTextPane为默认属性?

4

2 回答 2

3

清空jtextpane并重新添加新文本问题可以通过多种方式解决:

在此处调用doc.setCharacterAttributes(0, 1, attrs, true); 并传递一个空的 AttributeSet

重新创建文档,而不是doc.remove()/insert()调用jtp.setDocument(jtp.getEditorKit().createDefaultDocument())

清除输入属性。添加插入符号侦听器并检查文档是否为空。当它为空时,删除所有所需的属性。

于 2014-08-11T10:28:29.173 回答
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);
        }
于 2014-08-11T10:28:22.913 回答