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?

Community
  • 1
  • 1
phil294
  • 10,038
  • 8
  • 65
  • 98

1 Answers1

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)
StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • The first suggestion doesn't work: java.lang.ClassCastException: javax.swing.text.DefaultStyledDocument cannot be cast to javax.swing.text.html.HTMLDocument – Dominik Dec 30 '20 at 16:55
  • @Dominik obviously your textPane has not HTMLEditorKit. Try to call `textPane.setEditorKit(new HTMLEditorKit())` before. – StanislavL Jan 11 '21 at 06:56