0

当我尝试运行我的应用程序时,出现此错误:

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

第 19 行是这个私有 WebEngine engine = view.getEngine();

这是课程:

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);
}

但是当我做 WebView view = new WebView 它会工作但它不会在启动时打开页面

我确实在scenebuilder中设置了fx-id

4

1 回答 1

5

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);
}
于 2014-12-14T15:41:35.177 回答