JTextPane append HTML string
Asked Answered
G

1

3

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?

Gloriane answered 16/12, 2014 at 19:41 Comment(0)
C
5

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)
Conic answered 17/12, 2014 at 6:5 Comment(2)
The first suggestion doesn't work: java.lang.ClassCastException: javax.swing.text.DefaultStyledDocument cannot be cast to javax.swing.text.html.HTMLDocumentKnot
@Knot obviously your textPane has not HTMLEditorKit. Try to call textPane.setEditorKit(new HTMLEditorKit()) before.Conic

© 2022 - 2024 — McMap. All rights reserved.