JTextPane的setContentType("text/html")无法正常工作

Dra*_*gon 7 html java swing jtextpane

当你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
    //...
}
Run Code Online (Sandbox Code Playgroud)

一般来说,我有一个由JTextPane表示的聊天.我从服务器接收消息,处理它们 - 为特定情况设置文本颜色,将微笑标记更改为图像路径等.所有内容都在HTML的范围内进行.但是从上面的例子中可以清楚地看到,只有setText是setContentType("text/html")的主题,第二部分,其中添加的新消息由"text/plain"表示(如果我没有弄错的话) ).

是否可以将"text/html"内容类型应用于插入到JTextPane的所有数据?没有它,如果不实现非常复杂的算法,几乎不可能处理消息.

cam*_*ckr 10

我不认为你应该使用insertString()方法来添加文本.我认为你应该使用类似的东西:

JTextPane textPane = new JTextPane();
textPane.setContentType( "text/html" );
textPane.setEditable(false);
HTMLDocument doc = (HTMLDocument)textPane.getDocument();
HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
String text = "<a href=\"abc\">hyperlink</a>";
editorKit.insertHTML(doc, doc.getLength(), text, 0, 0, null);
Run Code Online (Sandbox Code Playgroud)