[英]How to load local html file in java swing?
我有一个树列表,当我单击一个节点时,它将打开一个特定的 html 文件。 我尝试将我的 html 加载到 Jeditorpanel 中,但它似乎无法正常工作。
这是我的主文件中的代码:
private void treeItemMouseClicked(java.awt.event.MouseEvent evt) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) treeItem.getSelectionPath().getLastPathComponent();
String checkLeaf = selectedNode.getUserObject().toString();
if (checkLeaf == "Java Turtorial 1") {
String htmlURL = "/htmlFILE/javaTurtorial1.html";
new displayHTML(htmlURL).setVisible(true);
}
}
我想在哪里显示它:
public displayHTML(String htmlURL) {
initComponents();
try {
//Display html file
editorHTML.setPage(htmlURL);
} catch (IOException ex) {
Logger.getLogger(displayHTML.class.getName()).log(Level.SEVERE, null, ex);
}
}
我的文件:
使用 JEditorPane 呈现 HTML 的一种简单方法是使用它的setText
方法:
JEditorPane editorPane =...
editorPane.setContentType( "text/html" );
editorPane.setText( "<html><body><h1>I'm an html to render</h1></body></html>" );
请注意,只有某些 HTML 页面(相对简单的页面)可以使用此 JEditoPane 呈现,如果您需要更复杂的内容,则必须使用第三方组件
根据 OP 的评论,我正在为答案添加更新:
更新
由于您尝试加载的 HTML 是 JAR 中的文件,因此您应该将文件读入某个字符串变量并使用上述方法setText
请注意,您不应使用java.io.File
,因为它用于识别文件系统中的资源,并且您正在尝试访问工件内部的某些内容:
像这样读取资源可以通过以下结构来完成:
InputStream is = getClass().getResourceAsStream("/htmls/myhtml.html");
// and then read with the help of variety of ways, depending on Java Version of your choice and by the availaility by auxiliary thirdparties
// here is the most simple way IMO for Java 9+
String htmlString = new String(input.readAllBytes(), StandardCharsets.UTF_8);
在此处阅读有关将 InputStream 读入 String 的许多不同方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.