3

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

4

3 回答 3

8

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

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

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

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

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

textPane1.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "<br/>\n")
于 2009-11-05T16:32:55.690 回答
0

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

于 2009-10-07T02:04:20.323 回答
0

我为此苦苦挣扎了半天。这在 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);
于 2012-03-04T06:59:09.413 回答