【问题标题】:JTextPane append HTML stringJTextPane 追加 HTML 字符串
【发布时间】:2015-02-15 05:38:39
【问题描述】:

我可以解析 JTextPane 的内容,而不会出现 HTML 中的任何问题:

textPane = new JTextPane();
textPane.setContentType("text/html");
textPane.setText(<b>Hello!</b>);
// ...
setVisible(true);

这导致

你好!

但每当我尝试将字符串附加到 textPane 时,使用

styledDoc = (StyledDocument) textPane.getStyledDocument();
styledDoc.insertString(styledDoc .getLength(), <b>Goodbye!</b>, null );

(如in this question所见),我的输出是

你好! &lt;b&gt;Goodbye!&lt;/b&gt;

(不带空格) - 因此跳过 html 格式。

如何将字符串附加到我的 JTextPane 对象并保留添加部分的 HTML 格式?

【问题讨论】:

    标签: java html formatting append jtextpane


    【解决方案1】:

    使用例如

    HTMLDocument doc=(HTMLDocument) textPane.getStyledDocument();
    doc.insertAfterEnd(doc.getCharacterElement(doc.getLength()),"<b>Goodbye!</b>");
    

    或者

    HTMLEditorKit kit=(HTMLEditorKit )textPane.getEditorKit();
    

    如果您想插入段落/表格或其他分支元素,请使用该方法

    public void insertHTML(HTMLDocument doc, int offset, String html,
                           int popDepth, int pushDepth,
                           HTML.Tag insertTag)
    

    【讨论】:

    • 第一个建议不起作用:java.lang.ClassCastException: javax.swing.text.DefaultStyledDocument 无法转换为 javax.swing.text.html.HTMLDocument
    • @Dominik 显然您的 textPane 没有 HTMLEditorKit。尝试之前拨打textPane.setEditorKit(new HTMLEditorKit())
    猜你喜欢
    • 2013-07-20
    • 2011-12-24
    • 2011-08-24
    • 2019-02-04
    • 2011-05-02
    • 2013-03-18
    • 2012-07-20
    相关资源
    最近更新 更多