代码之家  ›  专栏  ›  技术社区  ›  Bruno Arana Roa

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

  •  0
  • Bruno Arana Roa  · 技术社区  · 11 年前

    这两者有什么区别

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

    这个呢?

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

    我知道第二行没有打印消息,但为什么!?我正在聊天,新消息应该出现在前一条消息下面(就像在正常聊天中一样),但第一行新消息会出现在所有对话中。

    我使用内容类型为HTML的JEditorPane,因为聊天内容是笑脸之类的,如果我将内容类型更改为textPlain,第二行就可以完美地工作。

    我正在寻找解决方案,并使用文档和属性找到insertString,但我不知道它是如何使用的,以及它是否能解决我的问题。

    2 回复  |  直到 11 年前
        1
  •  0
  •   Adonais    11 年前

    我不知道为什么。然而,我知道,这与在 </html> 标签当你 setText() 在带有的JEditorPane上 text/html 内容类型, <html> 标签会自动添加。

    我以前也处理过类似的问题。我修复它的方法是将所有文本保存在一个字符串中,然后在窗格中进行设置:

    String s = "";
    ...
    s += msg;
    conversationPane.setText(s);
    
        2
  •  0
  •   user2053898    10 年前

    使用HTMLDocument中的insertBeforeStart方法。 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 "" )); }