如何在Jtextpane中添加到现有HTML [英] How to add to existing HTML in Jtextpane

查看:262
本文介绍了如何在Jtextpane中添加到现有HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java/Swing编写聊天程序,并且文本在Jtextpane对象中呈现.现在,新消息删除了旧消息,因为我不知道如何添加到现有文档中.该怎么做?

I am making a chat program in Java/Swing, and the text is rendered in a Jtextpane object. Right now, a new message erases the old one, as I couldn't figure out how to add to the existing document. How to do this?

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.

相反,只需使用常规文本,然后您就可以将文本与样式属性相关联.

Instead just use regular text and then you can associate the text with styled attributes.

例如:

//  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) {}

这篇关于如何在Jtextpane中添加到现有HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆