1

我试图解决在安装了 HTMLEditorKit 的情况下使用 JEditorPane.getText() 时出现的不一致问题。

我可以使用 JEditorPane.setText 传递包含 <br> 标记的 HTML 字符串,当我使用 getText() 时,这些换行符正确显示为 <br>。但是当用户在 JEditorPane 中输入一个换行符时,getText() 返回一个“/n”字符而不是 <br> 标记。我的自定义 HTML 解析器无法区分用户“/n”字符和添加的“/n”字符——看起来——以使 HTML 字符串看起来更漂亮。一个例子:

如果用户输入一些文本,JEditorPane.getText() 过程将返回如下内容:

<html>
  <head>

  </head>
  <body>
    I've written some text! Indeed so much text that this line is probably 
    going to word wrap when I run the getText procedure!

And now I just hit enter a few times! I wonder what will happen if it wraps 
    another time? WHAM.
And I'll hit enter once more for good measure.
  </body>
</html>

而我希望这会显示为:

<html>
  <head>

  </head>
  <body>
    I've written some text! Indeed so much text that this line is probably 
    going to word wrap when I run the getText procedure!<br><br>And now I 
    just hit enter a few times! I wonder what will happen if it wraps 
    another time? WHAM.<br>And I'll hit enter once more for good measure.
  </body>
</html>

当用户点击回车时,有什么方法可以将 <br> 插入到 getText 字符串中?我的第一次尝试是使用 documentFilter,但文档说我只是大声使用过滤器中的 insertString 或 filterBypass,因此我不能使用 setText (“< br>”) 路由。经过大量阅读,我在想另一种选择是扩展 HTMLEditorKit 并覆盖读取过程?JTextComponents 对我来说是新的,所以这超出了我的想象。还有其他选择吗?还是资源?

谢谢!

4

2 回答 2

1

您可以使用 DocumentListener 并跟踪 \n 插入。在插入时为插入的 \n 创建一个虚拟元素并将其替换为外部 html(使用 HTMLDocument 的 setOuterElement() 方法)。

在此处查看自动替换微笑的示例

于 2014-11-10T09:30:42.960 回答
0

知道了。

我的初始化看起来像这样:

HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = new HTMLDocument();
editor_pane.setEditorKit(kit);
editor_pane.setDocument(doc);

但这似乎不足以让文档处理所有用户输入。不幸的是,正确处理StyledEditorKit.BoldActionStyledEditorKit.ItalicAction就足够了,这就是为什么我认为问题不在于初始化的原因。

HTMLEditorKit kit = new HTMLEditorKit();
editor_pane.setEditorKit(kit);
editor_pane.setContentType("text/html");

按照@StanislavL 分享的文章中的建议,我将初始化更改为上述内容。通过这个更正,JEditorPane 现在会在用户按 Enter 键时创建新段落,这对我的目的来说已经足够了。谢谢您的帮助!

于 2014-11-12T03:27:39.803 回答