8

当您 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 的所有数据?没有它,几乎不可能在不实现非常复杂的算法的情况下处理消息。

4

3 回答 3

12

我认为您不应该使用 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);
于 2013-02-27T22:32:23.730 回答
3

重新编辑

抱歉,我误解了问题:将字符串插入为 HTML。为此,需要借助 HTMLEditorKit 功能:

            StyledDocument styleDoc = textPane.getStyledDocument();
            HTMLDocument doc = (HTMLDocument)styleDoc;
            Element last = doc.getParagraphElement(doc.getLength());
            try {
                doc.insertBeforeEnd(last, messages[1] + "<br>");
            } catch (BadLocationException ex) {
            } catch (IOException ex) {
            }
于 2013-02-27T21:25:51.490 回答
1

这是一种更简单的方法。

JTextPane pane = new JTextPane();
pane.setContentType("text/html");

pane.setText("<html><h1>My First Heading</h1><p>My first paragraph.</p></body></html>");
于 2015-07-02T00:37:14.403 回答