HTML JTextPane换行支持

时间:2009-10-06 17:39:07

标签: java swing jtextpane

我正在使用JTextPane编辑HTML。当我在GUI组件中输入换行符并在JTextPane上调用getText()时,我得到一个带换行符的字符串。如果我然后创建一个新的JTextPane并传入相同的文本,则会忽略换行符。

为什么JTextPane不插入< br>输入换行符时标记?对此有一个很好的解决方法吗?

    JTextPane test = new JTextPane();
    test.setPreferredSize(new Dimension(300, 300));
    test.setContentType("text/html");
    test.setText("Try entering some newline characters.");
    JOptionPane.showMessageDialog(null, test);
    String testText = test.getText();
    System.out.println("Got text: " + testText);
    // try again
    test.setText(testText);
    JOptionPane.showMessageDialog(null, test);
    testText = test.getText();
    System.out.println("Got text: " + testText);        

示例输出:

<html>
  <head>

  </head>
  <body>
    Try entering some newline characters.
What gives?
  </body>
</html>

我意识到我可以在调用setText之前将换行符转换为HTML换行符,但这也会在HTML和BODY标记之后转换换行符,并且看起来很愚蠢。

3 个答案:

答案 0 :(得分:8)

我已经解决了这个问题,问题是我在setText中传入的纯文本。如果我取消对setText的调用,则JTextPane.getText()的结果是格式正确的HTML,并且正确编码了换行符。

我相信当我致电JTextPane.setText("Try entering some newline characters")时,它会将HTMLDocument.documentProperties.__EndOfLine__设置为“\ n”。此文档属性常量定义为here

解决方案是确保在将文本传递给JTextPane.setText()方法时将文本包装在<p>标记中(注意,style属性用于任何后续段落):

textPane1.setText("<p style=\"margin-top: 0\">Try entering some newline characters</p>");

或者,在传入纯文本后,替换EndOfLineStringProperty(这更像是一个hack,我不推荐它):

textPane1.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "<br/>\n")

答案 1 :(得分:0)

看起来HTMLWriter类占用新行并且不读取它或将其转换为HTML(参见HTMLWriter中的第483行)。我没有看到一个简单的方法,因为它似乎是硬编码检查'\ n'。您可以将JTextPane文档的DefaultEditorKit.EndOfLineStringProperty属性(通过getDocument(。。putProperty)设置为&lt; br&gt;然后重写setText以用&lt; br&gt;替换“\ n”。虽然这会做你的建议并在html,head和body标签之间添加中断,所以你可能只想在body标签中进行替换。似乎没有一种非常直接的方法可以做到这一点。

答案 2 :(得分:0)

我在这个问题上挣扎了半天。这在Java 7中仍然存在。问题是将用户输入的新行保留在JEditorPane中(对于HTML内容类型)。当我在用户输入的“\ n”中添加一个标记键“\ _”时,我只能保留HTML中的新行(仍需要“\ n”以在编辑器中显示新行)然后将其替换为一个“\ n&lt; br /&gt;”当我把整个内容拉出来并放在不同的JEditorPane或任何所需的HTML时。我只在Windows上测试过这个。

((AbstractDocument) jEditorPane.getDocument()).setDocumentFilter(new HtmlLineBreakDocumentFilter());

// appears to only affect user keystrokes - not getText() and setText() as claimed
public class HtmlLineBreakDocumentFilter extends DocumentFilter
{
    public void insertString(DocumentFilter.FilterBypass fb, int offs, String str, AttributeSet a)
                        throws BadLocationException
    {
        super.insertString(fb, offs, str.replaceAll("\n", "\n\r"), a); // works
    }

    public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)
        throws BadLocationException
    {
        super.replace(fb, offs, length, str.replaceAll("\n", "\n\r"), a); // works
    }
}


String str = jEditorPane.getText().replaceAll("\r", "<br/>"); // works
jEditorPane2.setText(str);