First of all, i set the JTextPane like this:
HTMLEditorKit editorKit = new HTMLEditorKit();
HTMLDocument document = (HTMLDocument) editorKit.createDefaultDoc
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 JTextPane
first and then set the line spacing.
* @param the JTextPane
to apply the change
* @param factor the factor of line spacing. For example, 1.0f
.
* @param replace whether the new AttributeSet
should replace the old set. If set to false
, 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