javautf-8fontsheightjtextpane

Java JTextPane changes line height when UTF8 character is added


I am using Java JDK 1.6 and have a problem using JTextPane to show text with a monospaced font. As soon as I add a UTF8-character like 😂, the line height in the textpane is reduced (for all the text already in the pane and also all text added later). How can I avoid this? I would like to have the normal line height.

Here is some sample code:

    class AttributedTextPane extends JTextPane
    {

        private DefaultStyledDocument defaultStyledDocument;

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

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

This pane is integrated into an JInternalFrame. Creating the panel and setting the desired monospaced font:

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

To display the desired text, I call pane.setText(...); As soon as I add the UTF8 character, the line height changes, see screenshot at https://i.sstatic.net/hBZDe.png. Is there a way to avoid that the line height is changed? Thanks, Deejay


Solution

  • You could try setting/forcing a line height like so:

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

    Source:

    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)