JavaFX resource handling: Load HTML files in WebView

You get this exception because your url variable is null on this line:

String url = WebViewSample.class.getResource("/map.html").toExternalForm();

You have several options with getResource():

If the resource is the same directory as the class, then you can use

String url = WebViewSample.class.getResource("map.html").toExternalForm();

Using beginning slash(“https://stackoverflow.com/”) means relative path to the project root.:

In your particular case, if the resource is stored in the webviewsample package, you can get the resource as:

String url = WebViewSample.class.getResource("/webviewsample/map.html").toExternalForm();

Using a beginning dot-slash(“./”) means relative path to path of the class:

Imagine that you rclass is stored in package webviewsample, and your resource (map.html) is stored in a subdirectory res. You can use this command to get the URL:

String url = WebViewSample.class.getResource("./res/map.html").toExternalForm();

Based on this, if your resource is in the same directory with your class, then:

String url = WebViewSample.class.getResource("map.html").toExternalForm();

and

String url = WebViewSample.class.getResource("./map.html").toExternalForm();

are equivalent.

For further reading you can check the documentation of getResource().

Leave a Comment