Search code examples
javahtmlformattingappendjtextpane

JTextPane append HTML string


I can parse the content of a JTextPane witout any problems in HTML:

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

this results in

Hello!

But whenever I try to append a String to textPane, using

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

(as seen in this question), my output is

Hello! <b>Goodbye!</b>

(without whitespaces) - so the html formatting is skipped.

How can I append a String to my JTextPane Object and keep the HTML formation for the added part?


Solution

  • Use e.g.

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

    Or

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

    and use the method if you would like to insert paragraph/table or another branch element

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