2016-11-07 10 views
0

При создании отображения в моем основном цикле загрузчик для AnchorPane FXML возвращает null при вызове getController().Метод 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);