JavaFX - getScene() 返回 null [英] JavaFX - getScene() returns null

查看:39
本文介绍了JavaFX - getScene() 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 JavaFX Scene Builder 构建一个小型应用程序.

I just started using JavaFX Scene Builder to build a small application.

它由属于login.fxml"的控制器类Login.java"组成,其中通过名为registrationClicked(ActionEvent event)"的方法加载FXML文件registrierung.fxml":

It is made up of a controller class 'Login.java' which belongs to 'login.fxml', in which the FXML file 'registrierung.fxml' is loaded via a method called 'registrationClicked(ActionEvent event)':

public class Login {

@FXML
private void registrationClicked(ActionEvent event){
    try{
        ((Node) (event.getSource())).getScene().getWindow().hide();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/fxml/registrierung.fxml"));
        Parent root = (Parent) loader.load();
        Stage stage = new Stage();
        Scene scene = new Scene(root);      
        stage.setTitle("Registration");
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    } catch(IOException e){
        e.printStackTrace();
    }
}

现在我想通过根节点 vboxRoot 获得对控制器类Registrierung.java"中registrierung.fxml"阶段的引用:

Now I want to get a reference to the stage of 'registrierung.fxml' in the controller class 'Registrierung.java' via the root node vboxRoot:

@FXML
private VBox vboxRoot;

Stage stage = (Stage) vboxRoot.getScene().getWindow();

然而,'getScene()' 总是会导致 NullPointerException.两个 FXML 文件的控制器类都在 Scene Builder 中进行了调整.

However 'getScene()' always leads to a NullPointerException. The controller classes for both FXML files are adjusted in Scene Builder.

这是我在registrierung.fxml"中设置 rood 节点的方式:

This is how I set up the rood node in 'registrierung.fxml':

<VBox fx:id="vboxRoot" maxHeight="-Infinity" maxWidth="-Infinity" prefHeight="267.0" prefWidth="355.0" stylesheets="@../css/styles.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="businesslogik.Registrierung">

我做错了什么?

推荐答案

您正在尝试为尚未初始化的对象获取场景.如果你在

you are trying to get the scene for an object that has not been initialized yet. if you were doing the same operation in

@Override 
    public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
    Stage stage = (Stage) vboxRoot.getScene().getWindow();
}

或者如果您有一个在您单击某物时触发的事件(在场景加载后执行)

or if you have an event that triggers once you click something (which executes after the scene has loaded)

@FXML
private void action(ActionEvent event) throws IOException {
    Stage stage = (Stage) vboxRoot.getScene().getWindow();
}

这行得通!

这篇关于JavaFX - getScene() 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆