我目前使用 JTextPane 来允许用户添加/编辑文本。它允许粗体/斜体/下划线(我计划将来允许链接)。它还允许用户放入按钮,这些按钮作为自定义样式插入。面板看起来像:
<<图片已删除>>
我希望能够将内容保存/加载为 HTML - 内容将合并到 Flash swf 中。我能够像这样以 HTML 格式获取内容:
public String getHTMLText(){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try{
HTMLEditorKit hk = new HTMLEditorKit();
hk.write(baos, this.getStyledDocument(), 0, this.getDocument().getLength());
} catch (IOException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
return baos.toString();
}
如果 JTextPane 仅包含粗体/斜体/下划线文本,则此方法可以正常工作。虽然输出过于复杂。我也希望能够输出我的自定义样式,但是当我尝试时出现此错误:
Exception occurred during event dispatching:
java.lang.NullPointerException
at javax.swing.text.html.MinimalHTMLWriter.writeAttributes(MinimalHTMLWriter.java:151)
at javax.swing.text.html.MinimalHTMLWriter.writeStyles(MinimalHTMLWriter.java:256)
at javax.swing.text.html.MinimalHTMLWriter.writeHeader(MinimalHTMLWriter.java:220)
at javax.swing.text.html.MinimalHTMLWriter.write(MinimalHTMLWriter.java:122)
at javax.swing.text.html.HTMLEditorKit.write(HTMLEditorKit.java:293)
at javax.swing.text.DefaultEditorKit.write(DefaultEditorKit.java:152)
at numeracy.referencetextpanel.NRefButtonTextArea.getHTMLText(NRefButtonTextArea.java:328)
at numeracy.referencetextpanel.NInputPanelRefTextButton.getReferencedText(NInputPanelRefTextButton.java:59)
at numeracy.referencetextpanel.NInputRefText.actionPerformed(NInputRefText.java:106)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
我的自定义样式是这样插入的(cID 是像“{0-0}”这样的字符串):
StyledDocument doc = this.getStyledDocument();
NRefButton b = this.createRefButton(cID);
Style style = doc.addStyle(cID, null); //prepare a style
StyleConstants.setComponent(style, b);
doc.insertString(doc.getLength(), b.toString(), style); //insert button at index
函数 createRefButton(String cID):
private NRefButton createRefButton(String cID) {
NRefButton b = new NRefButton(_equationButtons.get(cID).getText(), cID, _equationButtons.get(cID).isStruck()); //prepare a button
return b;
}
NRefButton 覆盖 toString,它返回 "{"+cID+"}"。
我想知道的是:我应该修改插入“样式”的方式来得到这个错误吗?
有没有一种不同/更好的方法可以让我从此 JTextPane 获取 HTML?我想要的只是粗体/斜体/下划线文本周围的 HTML 标签,而不是过于复杂,因为我必须去掉不必要的 HTML,并且“样式”以 button.toString() 的形式出现。
或者我应该实现自己的 toHTML() 方法,用所需的标签包裹粗体/斜体/下划线文本?我不介意这样做(在某些方面我更喜欢它),但我不知道如何获取给定 JTextPane 文档的样式。我想如果我能够获得这些样式,我可以遍历它们,将样式文本包装在适当的标签中?
理想情况下,图示的 JTextPane 内容将输出为:
<html><p>This is some <b>styled</b> text. It is <u>incredible</u>.
<br/>
<br/>
Here we have a button that has been dropped in: {0-0}. These buttons are a <b><i>required part of this project.</i></b>
我也希望能够将输出 HTML读入JTextPane - 我不介意为此编写自己的 fromHTML() 方法,但我需要能够先获取 HTML。
感谢您花时间阅读我的问题。