java - java - 如何在java swing中加载本地html文件?
问题描述
我有一个树列表,当我单击一个节点时,它将打开一个特定的 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 的许多不同方法
推荐阅读
- r - R在轴上绘制符号未正确显示
- android - 如何使用 React Native 更改 Google Mapview Polyline Stroke Style Dashed Style Line?
- javascript - VM1661:1 Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0
- spring-profiles - 无法在 bootstrap.yml 或 application.yml 上定义配置文件
- angular - 错误:node_modules/@types/d3-dsv/index.d.ts(159,60):错误 TS1005:“,”预期
- datetime - 无法在 Go 中解析有效时间
- ssl - 从anypoint studio连接heroku上的Apache kafka时出现SSL握手异常
- javascript - JavaScript - SVG 文本返回“未定义”
- sql - 如何从 Metabase 中的 .sql 文件创建数据库
- next.js - 在 Next.js 的 SSR 期间 Vercel 使用什么时区?