Java JTextPane 在添加 UTF8 字符时更改行高

Java JTextPane changes line height when UTF8 character is added

我正在使用 Java JDK 1.6,但在使用 JTextPane 显示具有等宽字体的文本时遇到问题。一旦我添加一个像 这样的 UTF8 字符,文本窗格中的行高就会降低(对于窗格中已经存在的所有文本以及稍后添加的所有文本)。我怎样才能避免这种情况?我想要正常的行高。

下面是一些示例代码:

    class AttributedTextPane extends JTextPane
    {

        private DefaultStyledDocument defaultStyledDocument;

        protected AttributedTextPane()
        {
            this.defaultStyledDocument = new DefaultStyledDocument();
            this.setDocument(defaultStyledDocument);

            this.setContentType("text/plain");
            ...
        }
    }
    ...

此窗格已集成到 JInternalFrame 中。创建面板并设置所需的等宽字体:

    Font font = new Font("DejaVu Sans Mono", Font.PLAIN, 11);
    AttributedTextPane pane = new AttributedTextPane();
    pane.setFont(font);

为了显示所需的文本,我调用了 pane.setText(...);一旦我添加 UTF8 字符,行高就会改变,请参见 http://i.imgur.com/Fq7XBJB.png 处的屏幕截图。有没有办法避免改变行高? 谢谢,播音员

您可以尝试 setting/forcing 像这样的行高:

MutableAttributeSet jTextPaneSet = new SimpleAttributeSet(pane.getParagraphAttributes());
StyleConstants.setLineSpacing(jTextPaneSet, 1.5f); //replace float 1.5f with your desired line spacing/height

来源:

http://docs.oracle.com/javase/8/docs/api/javax/swing/JTextPane.html#setParagraphAttributes(javax.swing.text.AttributeSet,%20boolean)

https://docs.oracle.com/javase/7/docs/api/javax/swing/text/StyleConstants.html#setLineSpacing(javax.swing.text.MutableAttributeSet,%20float)