FXMLLoader getController returns NULL?

后端 未结 1 647
感动是毒
感动是毒 2020-11-27 07:22

I have the main application class that does the following just fine:

   @Override
   public void start(Stage primaryStage) {
      try {
         FXMLLoader          


        
相关标签:
1条回答
  • 2020-11-27 08:01

    Change this

    @FXML
       public void editPerson() {
          try {
             FXMLLoader loader = new FXMLLoader(getClass().getResource(
                   "PersonEditor.fxml"));
             PersonEditorCtrl ctrl = loader.getController();
             ctrl.init(table.getSelectionModel().getSelectedItem());
             Parent root = (Parent) loader.load();
             Scene newScene = new Scene(root);
             Stage newStage = new Stage();
             newStage.setScene(newScene);
             newStage.show();
          } catch (Exception e) {
             e.printStackTrace();
          }
       }
    

    To that:

    @FXML
       public void editPerson() {
          try {
             FXMLLoader loader = new FXMLLoader(getClass().getResource(
                   "PersonEditor.fxml"));
             Parent root = (Parent) loader.load();
             PersonEditorCtrl ctrl = loader.getController();
             ctrl.init(table.getSelectionModel().getSelectedItem());
    
             Scene newScene = new Scene(root);
             Stage newStage = new Stage();
             newStage.setScene(newScene);
             newStage.show();
          } catch (Exception e) {
             e.printStackTrace();
          }
       }
    

    You first have to run loader.load() then you can get the Controller.

    Patrick

    0 讨论(0)
提交回复
热议问题