9

I want to load an HTMLfile in the WebView of my JavaFX application. The file is located in my project directory, inside webviewsample package.

I've used the following code :

public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("WebView test");             

    WebView  browser = new WebView();
    WebEngine engine = browser.getEngine();
    String url = WebViewSample.class.getResource("/map.html").toExternalForm();
    engine.load(url);

    StackPane sp = new StackPane();
    sp.getChildren().add(browser);

    Scene root = new Scene(sp);

    primaryStage.setScene(root);
    primaryStage.show();
}

But it throws an exception saying :

Exception in Application start method java.lang.reflect.InvocationTargetException

DVarga
  • 21,311
  • 6
  • 55
  • 60
Apar Adhikari
  • 741
  • 1
  • 6
  • 17

1 Answers1

18

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("/") 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().

DVarga
  • 21,311
  • 6
  • 55
  • 60