我在使jxbrowser在开发环境之外工作时遇到了麻烦。当我在eclipse中运行它时工作正常,但是当我编译它并运行屏幕似乎没有加载。这是我正在使用的代码:
browser = new Browser();
com.teamdev.jxbrowser.chromium.swing.BrowserView view = new com.teamdev.jxbrowser.chromium.swing.BrowserView(browser);
javax.swing.JFrame frame = new javax.swing.JFrame();
frame.add(view, java.awt.BorderLayout.CENTER);
frame.setSize(800, 450);
frame.setVisible(true);
browser.loadURL(Main.class.getResource("/assets/engine.html").toExternalForm());
我错过了什么吗?
答案 0 :(得分:0)
如果您的HTML资源"/assets/engine.html"
位于构建后的RPGItems.jar
内,默认情况下,Chromium引擎无法正确解析其路径。为了能够加载位于JAR存档内的资源,您必须使用以下实现注册自定义ProtocolHandler
:
BrowserContext browserContext = browser.getContext();
ProtocolService protocolService = browserContext.getProtocolService();
protocolService.setProtocolHandler("jar", new ProtocolHandler() {
@Override
public URLResponse onRequest(URLRequest request) {
try {
URLResponse response = new URLResponse();
URL path = new URL(request.getURL());
InputStream inputStream = path.openStream();
DataInputStream stream = new DataInputStream(inputStream);
byte[] data = new byte[stream.available()];
stream.readFully(data);
response.setData(data);
String mimeType = getMimeType(path.toString());
response.getHeaders().setHeader("Content-Type", mimeType);
return response;
} catch (Exception ignored) {}
return null;
}
});
此处的getMimeType
方法为给定的资源扩展返回适当的mime类型:
private static String getMimeType(String path) {
if (path.endsWith(".html")) {
return "text/html";
}
if (path.endsWith(".css")) {
return "text/css";
}
if (path.endsWith(".js")) {
return "text/javascript";
}
return "text/html";
}
注册ProtocolHandler
并定义支持的mime类型后,您可以使用标准Java和JxBrowser API从JAR存档加载资源:
browser.loadURL(Main.class.getResource("/assets/engine.html").toString());