简体   繁体   English

尝试将本地页面加载到JavaFX webEngine中

[英]Trying to load a local page into JavaFX webEngine

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文档(可能不正确)存储在以下位置:

我的HTML文档的位置

where com.cds.gui contains the class where I am attempting to load the file. 其中com.cds.gui包含我尝试加载文件的类。 If I print out webEngine.getDocument() I get null - ie the document isn't getting loaded. 如果我打印出webEngine.getDocument()我得到null - 即文档没有被加载。

Please let me know where I'm going wrong! 请让我知道我哪里出错了! Thanks. 谢谢。

You need to read the local file in as a URL so that the WebEngine can find it. 您需要以URL的形式读取本地文件,以便WebEngine可以找到它。 For instance, you can find the file as a resouce using 例如,您可以使用找到该文件作为资源

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. 或者,您可以将实际的String路径加载到File对象中,并使用它来获取String URL。

File f = new File("full\\path\\to\\webView\\main.html");
webEngine.load(f.toURI().toString());

Hope this helps! 希望这可以帮助!

You could use the file syntax for the URI eg 您可以使用URI的文件语法,例如

file:///C:/path/to/file.html (Windows)

https://en.wikipedia.org/wiki/File_URI_scheme https://en.wikipedia.org/wiki/File_URI_scheme

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM