当您 setContentType("text/html") 时,它仅适用于通过 JTextPane.setText() 设置的文本。通过样式放入 JTextPane 的所有其他文本对内容类型“免疫”。
这就是我的意思:
private final String[] messages = {"first msg", "second msg <img src=\"file:src/test/2.png\"/> yeah", "<img src=\"file:src/test/2.png\"/> third msg"};
public TestGUI() throws BadLocationException {
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setContentType("text/html");
//Read all the messages
StringBuilder text = new StringBuilder();
for (String msg : messages) {
textext.append(msg).append("<br/>");
}
textPane.setText(text.toString());
//Add new message
StyledDocument styleDoc = textPane.getStyledDocument();
styleDoc.insertString(styleDoc.getLength(), messages[1], null);
JScrollPane scrollPane = new JScrollPane(textPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//add scrollPane to the main window and launch
//...
}
一般来说,我有一个由 JTextPane 表示的聊天。我从服务器接收消息,处理它们 - 为特定情况设置文本颜色,将微笑标记更改为图像路径等。一切都是在 HTML 范围内完成的。但是从上面的例子可以清楚地看出,只有 setText 是 setContentType("text/html") 的主题,而第二部分,其中添加的新消息由 "text/plain" 表示(如果我没记错的话)。
是否可以将“text/html”内容类型应用于插入到 JTextPane 的所有数据?没有它,几乎不可能在不实现非常复杂的算法的情况下处理消息。