2016-11-07 200 views
0

在我的主循環中創建顯示時,AnchorPane FXML的加載器在調用getController()時返回null。Javafx FXMLLoader.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文檔中指定控制器?

回答

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);