How to open HTML file having another extension in JTextPane

守給你的承諾、 提交于 2019-12-11 07:39:49

问题


I have a HTML file and I need to display it in JTextPane.

editor.setPage("file:///" + new File("test-resources/test.html").getAbsoluteFile());

This works properly. It uses my modified HTML editor kit and displays special tags as needed. But modified file is not exactly HTML. It should have another extension. But that's a problem.

editor.setPage("file:///" + new File("test-resources/test.xhtbm").getAbsoluteFile());

The file has been just renamed and is being displayed as plain text now. Is there some way to force JTextPane to open HTML file with extension XHTBM as HTML file? Am I forced to use HTML extension if using JTextPane?


回答1:


One alternative is to use a JEditorPane and call JEditorPane.setContentType(String).

See setContentType(String) for details.

..For example if the type is specified as text/html; charset=EUC-JP the content will be loaded using the EditorKit registered for text/html and the Reader provided to the EditorKit to load unicode into the document will use the EUC-JP charset for translating to unicode..




回答2:


The solution has been found (see the post JEditorPane and custom editor kit):

public void openFile(String fileName) throws IOException {
    editor.setEditorKit(new ModifiedHTMLEditorKit());
    ModifiedHTMLDocument doc = (ModifiedHTMLDocument)editor.getDocument();
    try {
        editor.getEditorKit().read(new FileReader(fileName), doc, 0);
    }
    catch (BadLocationException b) {
        throw new IOException("Could not fill data into editor.", b);
    }
}

This is the proper technique.



来源:https://stackoverflow.com/questions/7525737/how-to-open-html-file-having-another-extension-in-jtextpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!