编程语言
首页 > 编程语言> > java-JTextPane附加HTML字符串

java-JTextPane附加HTML字符串

作者:互联网

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

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

这导致

你好!

但是每当我尝试将String附加到textPane时,使用

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

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

Hello! <b>Goodbye!</b>

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

如何在我的JTextPane对象上附加一个字符串,并保持添加部分的HTML格式?

解决方法:

使用例如

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)

标签:jtextpane,html,java,formatting,append
来源: https://codeday.me/bug/20191013/1904468.html