JTextPane 追加 HTML 字符串字符串、JTextPane、HTML

2023-09-07 02:25:33 作者:我的女神是女汉纸i

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

如何将html改成字符串

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?

解决方案

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)