简体   繁体   English

如何使用insertString在带有HTML的JEditorPane上添加一行

[英]How to use insertString to append a line on a JEditorPane with HTML

What's the difference between this 这有什么区别

conversationPane.setText(msg + conversationPane.getText());

and this? 和这个?

conversationPane.setText(conversationPane.getText() + msg);

I know thah the second line does not print the message but Why!? 我知道第二行不显示消息,但是为什么! I'm making a chat and the new messages should appear below the previous message (Like in a normal chat) but with the first line the new messages appear up all the conversation. 我正在聊天,新消息应显示在上一条消息的下方(就像在普通聊天中一样),但在第一行中,新消息将出现在所有对话中。

I use JEditorPane whith content type HTML because the chat contents smileys and this things, if I change the content type to textPlain the second line works perfectly. 我使用JEditorPane的内容类型HTML,因为聊天内容带有笑脸,如果我将内容类型更改为textPlain,则第二行效果很好。

I'm looking for the solution and find things with insertString using a Document and Attributes but I don't undestand how used and if this can solve my problem. 我正在寻找解决方案,并使用Document和Attributes使用insertString查找内容,但我不理解如何使用以及是否可以解决我的问题。

I don't know exactly why. 我不知道为什么。 I know, however, it's related with text being appended after a </html> tag. 但是,我知道这与在</html>标记后附加文本有关。 When you setText() on a JEditorPane with text/html content type, <html> tags are automatically added. 在具有text/html内容类型的JEditorPane上设置setText()时,会自动添加<html>标记。

I dealt with a similar problem before. 我以前也处理过类似的问题。 The way I fixed it was saving all the text in a string, then setting it in the pane: 我修复它的方式是将所有文本保存在字符串中,然后在窗格中进行设置:

String s = "";
...
s += msg;
conversationPane.setText(s);

Use insertBeforeStart method from HTMLDocument. 使用HTMLDocument中的insertBeforeStart方法。 Scala example: Scala示例:

//set basic document structure
text = "<html><title></title><body><span id='Text'></span></body></html>"
//get Document as HTMLDocument
val htmlDoc = peer.getDocument.asInstanceOf[javax.swing.text.html.HTMLDocument]
//get span element with id=Text, before which text will be inserted
val bottomText = htmlDoc.getElement("Text")
//append function with optional line feed
def appendXml(xml:String, lineFeed:Boolean) = { htmlDoc.insertBeforeStart(bottomText, s + (if (lf) "<br>" else "" )); }

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

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