Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.load("/webView/main.html");

My html document is (possibly incorrectly) stored in the following location:

Location of my HTML document

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.

Please let me know where I'm going wrong! Thanks.

like image 476
TomRaikes Avatar asked Feb 29 '16 15:02

TomRaikes


Video Answer


3 Answers

Long tormented with the paths to the file, and this works for me (Maven project, folder resources):

WebEngine engine = html.getEngine();
            File f = new File(getClass().getClassLoader().getResource("html/about.htm").getFile());
            engine.load(f.toURI().toString());
like image 66
Дима Годиков Avatar answered Nov 09 '22 11:11

Дима Годиков


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 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 f = new File("full\\path\\to\\webView\\main.html");
webEngine.load(f.toURI().toString());

Hope this helps!

like image 37
Marian Avatar answered Nov 09 '22 12:11

Marian


You could use the file syntax for the URI e.g.

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

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

like image 34
ManoDestra Avatar answered Nov 09 '22 11:11

ManoDestra