我正在使用 StyleDocument 在 JTextPane 中显示我的内容。
我搜索了一段时间,发现我可以使用 HTMLEditorKit 将我从文本 Pane 中获取的文档写入文件。但是当我想用 HTMLEditorKit 读取这个文件时,它没有在正确的文档中解析。我得到两个不同的结果:
保存:
Document doc = textpane.getStyledDocument();
HTMLEditorKit kit = new HTMLEditorKit();
kit.write(new FileOutputStream("path"), doc, 0, doc.getLength());
加载(2 个版本):
HTMLEditorKit kit = new HTMLEditorKit();
Document doc = null;
Document doc2 = kit.createDefaultDocument();
kit.read(new FileInputStream("path"), doc, 0);
kit.read(new FileInputStream("path"), doc2, 0);
textpane.setDocument(doc);
textpane.setDocument(doc2);
最佳答案
初始化 JTextPane 时,添加以下行:textpane.setContentType("text/html");
将保存更改为如下所示:
Document document = textpane.getStyledDocument();
EditorKit kit = textpane.getEditorKit();
kit.write(new FileOutputStream(new File("path")), doc, 0, doc.getLength());
将加载更改为如下所示:
EditorKit kit = pane2.getEditorKit();
Document doc = kit.createDefaultDocument();
kit.read(new FileInputStream(new File("path")), doc, 0);
textpane.setDocument(doc);
在我的测试环境中使用此设置,我能够将
JTextPane
中的文本设置为一些 html,从 Pane 中获取 html,将其写入文件,然后从同一个文件中读回。我没有看到任何使用 HTMLEditorKit
的理由,因为您没有做任何特定于 html 的事情,但是您可以根据需要进行更改。关于java - 如何将html加载到样式文档,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15418439/