java - 如何添加到 Jtextpane 中的现有 HTML

标签 java swing htmleditorkit

我正在用 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);

}

最佳答案

不要使用 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) {}

关于java - 如何添加到 Jtextpane 中的现有 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32234501/

相关文章:

java - 当 Javadoc 标记不完整时,Maven 无法在 Java 8 中运行

java - Android 时间选择器弹出问题

java - 查找两种数据类型的第 n 个最接近的对象

c# - 如何在 C# 中实现与在 Java 中相同的覆盖体验?

java - 无序列表项目符号在 JEditorPane 中看起来像素化

java - 使用 MVC 绘制同心/旋转图形

java - JPanel 的滚动 Pane ?

java - JTable 和 JScrollpane 大小的问题

java - 在 HTMLEditorKit/JEditorPane 中强制使用 <strong> 而不是 <b>

java - 在 Jeditorpane 中的 html 文本中渲染图像的问题