【问题标题】:How to add to existing HTML in Jtextpane如何在 Jtextpane 中添加到现有 HTML
【发布时间】:2015-11-20 22:59:23
【问题描述】:

我正在用 Java/Swing 制作一个聊天程序,文本呈现在 Jtextpane 对象中。现在,一条新消息会删除旧消息,因为我不知道如何添加到现有文档中。如何做到这一点?

public void addMessage(String sender, String msg) throws BadLocationException, IOException{
    HTMLEditorKit kit = new HTMLEditorKit();
    HTMLDocument doc = new HTMLDocument();
    pane.setEditorKit(kit);
    pane.setDocument(doc);

    kit.insertHTML(doc, doc.getLength(), "<b>[" + sender + "]</b> " + msg, 0, 0, null);

}

【问题讨论】:

  • 如果你只做 pane.setText(pane.getText() + "[" + sender + "] " + msg) 会发生什么?
  • setText 不起作用。不管我做什么,都把事情留白。不过,我想通了。我基本上是个傻瓜:每次运行 addMessage 时我都在重新创建文档......所以只是在课程开始时公开这些文件来修复它。希望这对某人有帮助!

标签: java swing htmleditorkit


【解决方案1】:

不要使用 HTML。

而只是使用常规文本,然后您可以将文本与样式属性相关联。

例如:

//  create a set of attributes

Simple AttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.RED);
StyleConstants.setBackground(keyWord, Color.YELLOW);
StyleConstants.setBold(keyWord, true);

//  Add some text

try
{
    StyledDocument doc = textPane.getStyledDocument();
    doc.insertString(doc.getLength(), "\nEnd of text", keyWord );
}
catch(Exception e) {}

【讨论】:

    猜你喜欢
    • 2012-04-17
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    相关资源
    最近更新 更多