如何在JtextPane中设置行间距?

首先,我像这样设置JTextPane:

HTMLEditorKit editorKit = new HTMLEditorKit(); HTMLDocument document = (HTMLDocument) editorKit.createDefaultDocument(); JTextPane textPane = new JTextPane(); textPane.setContentType("text/html"); textPane.setDocument(document); 

我想在JtextPane中设置行间距,这是我的想法,但它无法工作:

 SimpleAttributeSet aSet = new SimpleAttributeSet(); StyleConstants.setLineSpacing(aSet, 50); textPane.setParagraphAttributes(aSet, false); 

我错了?

当你调用textPane.setParagraphAttributes(aSet, false); 它尝试将行间距应用于选择但未选择任何内容

换句话说

 document.setParagraphAttributes(0, document.getLength(), attr, replace); 

要设置JTextPane样式,您可以使用样式表: 查找HtmlEditorKit #setStyleSheet

 StyleSheet sh = editorKit.getStyleSheet(); sh.addRule("body {line-height: 50px}"); 

我正在努力解决这个问题,然后在方法的API中使用public void setParagraphAttributes(AttributeSet attr, boolean replace) ,我发现了这个:

如果存在选择,则属性将应用于与选择相交的段落。 如果没有选择,则属性将应用于当前插入符号位置的段落。

因此OP的方法可行, 但您必须在设置行间距之前应用textPane.selectAll() 您只需要执行一次,并且附加到此JTextPane所有文本将具有相同的行空间, 即使您在设置行间距时窗格中没有文本也是如此。 我在实例化时这样做。

因此,为我工作的代码是:

 /** * 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); } 

注意:它将用因子*(文本的行高)替换当前行间距,而不是因子*原始行间距 。 很奇怪。

如果JTextPaneJScrollPane并且文本的长度太长,它将滚动到最底部。 通常我们希望看到顶部。 要重置滚动的位置,最后可以添加:

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

PS:要设置段落边距,我们有:

 textPane.setMargin(new Insets(10, 5, 10, 5)); //top, left, bottom, right