Javafx FXMLLoader.getController()方法返回null

时间:2016-11-07 14:11:37

标签: javafx fxmlloader

在主循环中创建显示时,调用getController()时,AnchorPane FXML的加载器返回null。

    //instantiates the FXMLLoader class by calling default constructor
        //creates an FXMLLoader called loader
        FXMLLoader loader = new FXMLLoader();

        //finds the location of the FXML file to load
        loader.setLocation(mainApp.class.getResource("/wang/garage/view/ItemOverview.fxml"));

        //sets the AnchorPane in the FXML file to itemOverview
        //so that the AnchorPane is set to the display of the app
        AnchorPane itemOverview = (AnchorPane) loader.load();
        rootLayout.setCenter(itemOverview);

        //finds the controller of the itemOverview and
        //sets it to controller variable
        //then provides a reference of mainApp to controller to connect the two
        ItemOverviewController controller = loader.getController();//returns null
        controller.setMainApp(this);

我没有在FXML文档中指定控制器。如果我使用loader.load(),这是必要的吗?如果是这样,我应该如何在FXML文档中指定控制器?

1 个答案:

答案 0 :(得分:1)

如果您没有直接在Java代码中设置控制器,则需要在FXML文件中指定控制器类(否则FXMLLoader将不知道它应该创建的对象类型用作控制器。)

只需添加

即可
fx:controller="com.mycompany.myproject.ItemOverViewController

以通常的方式将属性赋予FXML文件的根元素。

或者,您可以从Java设置控制器:

//instantiates the FXMLLoader class by calling default constructor
//creates an FXMLLoader called loader
FXMLLoader loader = new FXMLLoader();

//finds the location of the FXML file to load
loader.setLocation(mainApp.class.getResource("/wang/garage/view/ItemOverview.fxml"));

// create a controller and set it in the loader:
ItemOverviewController controller = new ItemOverviewController();
loader.setController(controller);

//sets the AnchorPane in the FXML file to itemOverview
//so that the AnchorPane is set to the display of the app
AnchorPane itemOverview = (AnchorPane) loader.load();
rootLayout.setCenter(itemOverview);


//provide a reference of mainApp to controller to connect the two
controller.setMainApp(this);