How to set the line spacing in a JtextPane?

后端 未结 3 1087
予麋鹿
予麋鹿 2020-12-20 06:27

First of all, i set the JTextPane like this:

HTMLEditorKit editorKit = new HTMLEditorKit();
HTMLDocument document = (HTMLDocument) editorKit.createDefaultDoc         


        
相关标签:
3条回答
  • 2020-12-20 06:35

    When you call textPane.setParagraphAttributes(aSet, false); it tries to apply line spacing to selection but nothing is selected

    Call it another way

    document.setParagraphAttributes(0, document.getLength(), attr, replace);
    
    0 讨论(0)
  • 2020-12-20 06:48

    To style JTextPane you could use Stylesheets: Look for HtmlEditorKit#setStyleSheet

    StyleSheet sh = editorKit.getStyleSheet();
    sh.addRule("body {line-height: 50px}");
    
    0 讨论(0)
  • 2020-12-20 06:54

    I was struggling with this problem and then in the API of the method public void setParagraphAttributes(AttributeSet attr, boolean replace), I found this:

    If there is a selection, the attributes are applied to the paragraphs that intersect the selection. If there is no selection, the attributes are applied to the paragraph at the current caret position.

    So the approach of OP will work, but you must apply textPane.selectAll() before setting the line spacing. You only have to do it once, and all the text appended to this JTextPane will have the same line space, even though you may have no text in the pane when you set the line spacing. I do it when it's instantiated.

    Thus the code working for me is:

    /**
     * Select all the text of a <code>JTextPane</code> first and then set the line spacing.
     * @param the <code>JTextPane</code> to apply the change
     * @param factor the factor of line spacing. For example, <code>1.0f</code>.
     * @param replace whether the new <code>AttributeSet</code> should replace the old set. If set to <code>false</code>, will merge with the old one.
     */
    private void changeLineSpacing(JTextPane pane, float factor, boolean replace) {
        pane.selectAll();
        MutableAttributeSet set = new SimpleAttributeSet(pane.getParagraphAttributes());
        StyleConstants.setLineSpacing(set, factor);
        txtAtributosImpresora.setParagraphAttributes(set, replace);
    }
    

    Note: it will replace the current line spacing with factor*(line height of text), not factor * original line spacing. Strange enough.

    If the JTextPane is in a JScrollPane and the length of text is too long, it will scroll to the very bottom. Usually we want to see the top part. To reset the position of the scroll, at last you can add:

    pane.setCaretPosition(0); //scroll to the top at last.
    

    P.S.: To set the paragraph margin, we have:

    textPane.setMargin(new Insets(10, 5, 10, 5)); //top, left, bottom, right
    
    0 讨论(0)
提交回复
热议问题