0

我正在尝试设计一个更大的 GUI 的一部分,它将格式化一些文本以使其看起来不错。它应该能够以很多有趣的方式玩文字。添加边框,下划线,即任何我想对文本做的装饰目的。JTextPane 是实现此目的的方法吗?

在下面的示例中,我想decorateTextPane()显示两行具有不同字体的文本。但是每当我打电话时,textPane.setFont()我都会更改窗格中所有现有文本的字体。

public class OuterClass {
    InnerClass inner = new InnerClass();

    private class InnerClass {
        private JTextPane textPane = new JTextPane()

        public InnerClass() {
            StyledDocument doc = textPane.getStyledDocument();
            SimpleAttributeSet center = new SimpleAttributeSet();
            StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
            doc.setParagraphAttributes(0, doc.getLength(), center, false);
        }
    }

    public void decorateTextPane() {
        inner.textPane.setFont(New Font("Times New Roman", Font.PLAIN, 15));
        inner.textPane.setText("First string");
        inner.textPane.setFont(New Font("Calibri", Font.PLAIN, 15));
        inner.textPane.append("\nSecond string"); //my textPane class defines an append method.
    }
}
4

2 回答 2

2

您可以使用 a JEditorPane而不是 a,JTextPane因为它非常适合您要完成的任务。:)

从答案 Java JTextPane 更改所选文本的字体

下面有一个DocumentJEditorPane(显然也有 JTextPane),您可以使用getDocument(). 如果可以的话,您想将其转换为 a StyledDocument,然后您可以setCharacterAttributes对给定的字符执行诸如此类的操作。

示例:http: //java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html

于 2014-04-06T01:59:42.113 回答
0

useFont()在添加应该使用其指定字体的文本之前定义方法并使用它们是我目前的方法。它正在工作,我很满意,但如果有人有更好的答案,我仍然非常感兴趣:-)

public class OuterClass {
InnerClass inner = new InnerClass();

private class InnerClass {
    private JTextPane textPane = new JTextPane();
    private Font firstFont = new Font("Times New Roman", Font.PLAIN, 18);
    private Font secondFont = new Font("Calibri", Font.PLAIN, 14);
    StyledDocument doc = textPane.getStyledDocument();
    SimpleAttributeSet aSet = new SimpleAttributeSet();

    public InnerClass() {
        StyledDocument doc = textPane.getStyledDocument();
        SimpleAttributeSet center = new SimpleAttributeSet();
        StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
        doc.setParagraphAttributes(0, doc.getLength(), center, false);
    }

    public void useFont1() {
        StyleConstants.setFontFamily(aSet, firstFont.getFamily());
        StyleConstants.setFontSize(aSet, firstFont.getSize());
        doc.setParagraphAttributes(0, 0, aSet, false);
    }

    public void useFont2() {
        StyleConstants.setFontFamily(aSet, secondFont.getFamily());
        StyleConstants.setFontSize(aSet, secondFont.getSize());
        doc.setParagraphAttributes(doc.getLength(), 0, aSet, false);
    }
}

public void decorateTextPane() {
    inner.useFont1();
    inner.textPane.setText("First string");
    inner.useFont2();
    inner.textPane.append("\nSecond string"); //my textPane class defines an append method.
}

}

于 2014-04-06T13:50:38.417 回答