Swing Chat HTML 格式的消息

Swing Chat HTML formatted messages

我正在尝试制作一个 Swing 聊天客户端。我需要在 HTML.

中格式化历史通信中的消息

我试图用 JTextPane 解决的问题,因为它支持 HTML 格式化。我做的时候只是文字显示,原则上一切正常。

但是当我使用HTML标签添加表情时<img>,每次有新消息,window对应的所有文字都开始抽动。

我是怎么做到的:

jTextPane.setText ("message");

什么时候,新消息,我就这样做了

jTextPane.setText ("message" + "new message"); etc.

结果就是俄罗斯方块"snake"的原理。结果,我不喜欢它的工作方式。

所以请告诉我是否可以使用 JLabel 将新消息添加到 JScrollpane 来推断出这些新消息?如何使每个新的 post 成为一个单独的元素?

    String[] split = text.split("\t\t");

    String time = split[0].split("\t")[2].split(", ")[1];
    String sender = split[0].split("\t")[3];
    String message = split[1];

    if (!jTextPane.getText().equals("Please log in!")) {
        oldMsg = jTextPane.getText().substring(jTextPane.getText().indexOf("<body>") + 6, jTextPane.getText().lastIndexOf("</body>"));

        if(sender.equalsIgnoreCase(login.getText())) {
            msg = "<div style=\"text-align:right\">" + checkMsgOnSmile(message) + " " + "<b>" + " :" + checkSenderOnColor(sender) + "</b>" + "<span style=\"font-size:10pt\">[" + time + "]</span></div>";
        } else {
            msg = "<div style=\"\"><span style=\"font-size:10pt\">[" + time + "]</span> " + "<b>" + checkSenderOnColor(sender) + ":" + "</b>" + " " + checkMsgOnSmile(message);
        }

        String[] check = (oldMsg + msg).split("<br>");
        if (check.length > 99) {
            ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(check));
            arrayList.remove(0);
            String str = "";

            for (int i = 0; i < arrayList.size(); i++) {
                str = str + arrayList.get(i).toString() + "<br>";
            }

            jTextPane.setText(str);
        } else {
            oldMsg = oldMsg.replaceAll("<span><font size=\"10pt\">", "<span style=\"font-size:10pt\">");
            oldMsg = oldMsg.replaceAll("</font></span>", "</span>");
            jTextPane.setText(oldMsg + msg + "<br>");
        }
    }

可以用JLabel和JScrollPane代替吗?

如果您只需要显示具有不同颜色、字体等的文本,那么我发现使用文本和属性比使用 HTML 更容易。一个简单的例子是这样的代码:

JTextPane textPane = new JTextPane();
textPane.setText( "Hello:" );
textPane.setEditable(false);
StyledDocument doc = textPane.getStyledDocument();

//  Define a keyword attribute

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

//  Add some text

try
{
    doc.insertString(doc.getLength(), "\nAnother line of text", keyWord );
}
catch(Exception e) {}