首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FXMLLoader.getController()方法返回空

FXMLLoader.getController()方法返回空
EN

Stack Overflow用户
提问于 2016-11-07 14:11:36
回答 1查看 2K关注 0票数 0

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

代码语言:javascript
复制
    //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文档中指定控制器?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-07 14:20:54

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

只需添加

代码语言:javascript
复制
fx:controller="com.mycompany.myproject.ItemOverViewController

属性以通常的方式添加到FXML文件的根元素。

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

代码语言:javascript
复制
//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);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40467249

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档