繁体   English   中英

HTML JTextPane换行符支持

[英]HTML JTextPane newline support

我正在使用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标记之后转换换行符,而且看起来很愚蠢。

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

我相信当我调用JTextPane.setText("Try entering some newline characters")会将HTMLDocument.documentProperties.__EndOfLine__为“ \\ n”。 此文档属性常量在此处定义。

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

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

或者,在您输入纯文本之后,替换EndOfLineStringProperty(这更像是一种技巧,我不推荐这样做):

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

看起来HTMLWriter类吃掉了新行,并且不读取它或将其转换为HTML(请参见HTMLWriter中的483行)。 我没有找到解决此问题的简便方法,因为它似乎很难编码为检查“ \\ n”。 您可能可以将JTextPane文档的DefaultEditorKit.EndOfLineStringProperty属性(通过getDocument()。putProperty)设置为<br>,然后重写setText以将“ \\ n”替换为<br>。 虽然这样做可以完成您的建议,并在html,head和body标签之间添加断点,所以您可能只想在body标签中进行替换。 似乎没有一种非常直接的方法可以做到这一点。

我为此挣扎了半天。 这在Java 7中仍然没有解决。问题是将用户输入的新行保留在JEditorPane中(对于HTML内容类型)。 当我在用户输入的“ \\ n”处添加标记键“ \\ r”时,我只能在HTML中保留新行(仍然需要“ \\ n”才能在编辑器中显示新行),然后将其替换为当我拉出全部内容并放置在其他JEditorPane或所需的HTML中时,显示为“ \\ n <br/>”。 我只在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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM