JavaFX can't set WebView in FXML file

1.9k Views Asked by At

When i try to run my application i get this error:

Caused by: java.lang.NullPointerException
at WebOpenController.<init>(WebOpenController.java:19)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at java.lang.Class.newInstance(Class.java:438)
at sun.reflect.misc.ReflectUtil.newInstance(ReflectUtil.java:51)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:923)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:967)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:216)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:740)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2701)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2521)
... 22 more

Line 19 is this private WebEngine engine = view.getEngine();

and this is the class:

public class WebOpenController implements Initializable {

@FXML
private WebView view;

private String link = "http://google.com";

private WebEngine engine = view.getEngine();

@Override
public void initialize(URL location, ResourceBundle resources) {
    engine.load(link);
}

But when i do WebView view = new WebView it will work but it wont open the page on startup

and i did set the fx-id in scenebuilder

1

There are 1 best solutions below

0
On BEST ANSWER

You need to retrieve the web engine after the webview has been instantiated. Note that initialize() will be called after the contents from the fxml file have been completely loaded, so that's where you should do this. You can read about this here.

This will work:

@FXML
private WebView view;

private String link = "http://google.com";

private WebEngine engine;

@Override
public void initialize(URL url, ResourceBundle rb) {
    engine = view.getEngine();
    engine.load(link);
}