我正在使用StyleDocument在JTextPane中显示我的内容。 我搜索了一会儿,发现我可以用HTMLEditorKit写下从textpane到文件的文件。 但是当我想用HTMLEditorKit读取这个文件时,它不会在正确的文档中解析。 我得到两个不同的结果:
我在我的textpane中获得了简单的html代码 我的textpane中没有任何内容保存:
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);I'm using a StyleDocument to display my content in a JTextPane. I searched for a while and saw that I can write with the HTMLEditorKit the document I get from the textpane to a file. But when I want to read this file with the HTMLEditorKit it doesn't parse in the right document. I get two different results:
I get the plain html code in my textpane I get no content in my textpaneSaving:
Document doc = textpane.getStyledDocument(); HTMLEditorKit kit = new HTMLEditorKit(); kit.write(new FileOutputStream("path"), doc, 0, doc.getLength());Loading (2 versions):
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,从窗格中获取html,将其写入文件,然后从同一文件中读回。 我没有看到任何使用HTMLEditorKit理由,因为你没有做任何特定的HTML,但你可以根据需要改变它。
When you initialize your JTextPane add the following line: textpane.setContentType("text/html");
Change Saving to look like this:
Document document = textpane.getStyledDocument(); EditorKit kit = textpane.getEditorKit(); kit.write(new FileOutputStream(new File("path")), doc, 0, doc.getLength());Change Loading to look like this:
EditorKit kit = pane2.getEditorKit(); Document doc = kit.createDefaultDocument(); kit.read(new FileInputStream(new File("path")), doc, 0); textpane.setDocument(doc);Using this setup in my test environment I was able to set the text in a JTextPane to some html, get the html from the pane, write it to a file and subsequently read it back from that same file. I didn't see any reason to use a HTMLEditorKit as you are not doing anything html specific however you can change that as you see fit.
更多推荐
发布评论