Accessing FXML controller class

后端 未结 4 1248
再見小時候
再見小時候 2020-11-22 07:51

I would like to communicate with a FXML controller class at any time, to update information on the screen from the main application or other stages.

Is this possible

4条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 08:06

    Just to help clarify the accepted answer and maybe save a bit of time for others that are new to JavaFX:

    For a JavaFX FXML Application, NetBeans will auto-generate your start method in the main class as follows:

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
    
        Scene scene = new Scene(root);
    
        stage.setScene(scene);
        stage.show();
    }
    

    Now, all we need to do to have access to the controller class is to change the FXMLLoader load() method from the static implementation to an instantiated implementation and then we can use the instance's method to get the controller, like this:

    //Static global variable for the controller (where MyController is the name of your controller class
    static MyController myControllerHandle;
    
    @Override
    public void start(Stage stage) throws Exception {
        //Set up instance instead of using static load() method
        FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
        Parent root = loader.load();
    
        //Now we have access to getController() through the instance... don't forget the type cast
        myControllerHandle = (MyController)loader.getController();
    
        Scene scene = new Scene(root);
    
        stage.setScene(scene);
        stage.show();
    }
    

提交回复
热议问题