java 尝试将本地页面加载到 JavaFX webEngine
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35703884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to load a local page into JavaFX webEngine
提问by TomRaikes
I have a webView component on a tab in my JavaFX application which I am trying to load an locally stored HTML page into:
我的 JavaFX 应用程序的选项卡上有一个 webView 组件,我试图将本地存储的 HTML 页面加载到:
WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.load("/webView/main.html");
My html document is (possibly incorrectly) stored in the following location:
我的 html 文档(可能不正确)存储在以下位置:
where com.cds.gui contains the class where I am attempting to load the file. If I print out webEngine.getDocument()
I get null
- i.e. the document isn't getting loaded.
其中 com.cds.gui 包含我尝试加载文件的类。如果我打印出来,webEngine.getDocument()
我得到null
- 即文档没有被加载。
Please let me know where I'm going wrong! Thanks.
请让我知道我哪里出错了!谢谢。
回答by Marian
You need to read the local file in as a URL so that the WebEngine can find it. For instance, you can find the file as a resouce using
您需要将本地文件作为 URL 读取,以便 WebEngine 可以找到它。例如,您可以使用以下方法找到该文件作为资源
URL url = this.getClass().getResource("/com/cds/gui/webView/main.html");
webEngine.load(url.toString());
Or you can load the actual String path into a File object and use it to get the String URL.
或者您可以将实际的字符串路径加载到 File 对象中并使用它来获取字符串 URL。
File f = new File("full\path\to\webView\main.html");
webEngine.load(f.toURI().toString());
Hope this helps!
希望这可以帮助!
回答by ManoDestra
You could use the file syntax for the URI e.g.
您可以使用 URI 的文件语法,例如
file:///C:/path/to/file.html (Windows)
回答by Дима Годиков
Long tormented with the paths to the file, and this works for me (Maven project, folder resources):
长期被文件路径折磨,这对我有用(Maven项目,文件夹资源):
WebEngine engine = html.getEngine();
File f = new File(getClass().getClassLoader().getResource("html/about.htm").getFile());
engine.load(f.toURI().toString());