在我的主循环中创建显示时,AnchorPane的加载程序在调用getController()时返回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文档中指定控制器?
发布于 2016-11-07 14:20:54
如果没有在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);https://stackoverflow.com/questions/40467249
复制相似问题