2014-11-09 96 views
1

我想解决与安装HTMLEditorKit时使用JEditorPane.getText()不一致。JEditorPane与HTMLEditorKit返回换行符而不是<br>标记

我可以使用JEditorPane.setText传递包含< br>标签的HTML字符串,并且当我使用getText()时,这些新行将正确显示为< br>。但是当用户在JEditorPane中输入新行时,getText()会返回一个“/ n”字符而不是标签。我的自定义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> 

当用户输入时,是否有任何方法可以将<插入到getText字符串中?我第一次尝试使用documentFilter,但文档说我只是大声地在过滤器中使用insertString或filterBypass,因此我不能使用setText(“< br>”)路由。大量的阅读后,我想另一种选择是扩展HTMLEditorKit并重写读取过程? JTextComponents对我来说是新的,所以这是我的头。还有其他选择吗?或资源?

谢谢!

+0

您是否曾经发布SSCCE来说明问题? – StanislavL 2014-11-10 09:26:32

回答

0

明白了。

我的初始化是这样的:

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

但似乎这是不够的文件来处理所有的用户输入。不幸的是,它足够处理StyledEditorKit.BoldAction StyledEditorKit.ItalicAction正确,这就是为什么我不认为问题是在初始化。

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

我改变了上面的初始化,正如文章中@StanislavL共享的建议。通过这种修正,JEditorPane现在在用户输入时创建新的段落,这对我的目的来说已经足够了。谢谢您的帮助!

1

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

见例如autoreplace的微笑here