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
It supports Cascading Style Sheets (CSS), JavaScript, Document Object Model (DOM), and HTML5. The embedded browser enables you to perform the following tasks in your JavaFX applications: Render HTML content from local and remote URLs.
You can access the DOM of the web page displayed inside a JavaFX WebView by calling the WebEngine getDocument() method. Here is an example of accessing the DOM of a WebView : Document document = webEngine. getDocument();
WebView is a Node that manages a WebEngine and displays its content. The associated WebEngine is created automatically at construction time and cannot be changed afterwards. WebView handles mouse and some keyboard events, and manages scrolling automatically, so there's no need to put it into a ScrollPane .
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With