【问题标题】:How to set the line spacing in a JtextPane?如何在 JtextPane 中设置行距?
【发布时间】:2013-08-14 19:24:10
【问题描述】:

首先,我这样设置 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);

我错了吗?

【问题讨论】:

  • @Aleksei Bulgak 这不是我想回答的。我想要的是在运行时可以设置,并且可以通过textPane.getText()获取HTML代码。

标签: java swing line jtextpane spacing


【解决方案1】:

要设置 JTextPane 的样式,您可以使用样式表:Look for HtmlEditorKit#setStyleSheet

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

【讨论】:

    【解决方案2】:

    当您致电textPane.setParagraphAttributes(aSet, false); 它尝试将行距应用于选择,但没有选择任何内容

    换一种说法

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

    【讨论】:

    • 仍然没有变化。 StyledDocument 文档 = textWeight.getStyledDocument(); MutableAttributeSet set = new SimpleAttributeSet(); StyleConstants.setLineSpacing(set, 50); document.setParagraphAttributes(0, document.getLength(), set, false);
    【解决方案3】:

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

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

    所以OP的方法是可行的,但你必须在设置行距之前应用textPane.selectAll()你只需要做一次,所有附加到这个JTextPane的文本都会具有相同的行距,即使您在设置行距时窗格中可能没有文本。我在实例化时这样做。

    因此为我工作的代码是:

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

    注意:它会将当前行距替换为 factor*(文本行高),而不是 factor * 原始行距。够奇怪的。

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

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

    P.S.:要设置段落边距,我们有:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多