简体   繁体   English

JavaFX无法在FXML文件中设置WebView

[英]JavaFX can't set WebView in FXML file

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(); 第19行是此私有WebEngine引擎= 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 但是,当我执行WebView view = new WebView时,它可以工作,但启动时不会打开页面

and i did set the fx-id in scenebuilder 而且我确实在scenebuilder中设置了fx-id

You need to retrieve the web engine after the webview has been instantiated. 实例化Webview之后,您需要检索Web引擎。 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. 请注意,在完全加载fxml文件中的内容之后 ,将调用initialize() ,因此应在此处进行操作。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM