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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Very nice answer !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.