Search code examples
javajavafxcontrollerscene

How to get a handle of a new stage Controller JavaFX


I am starting a 2nd scene that uses it's own controller. I want to access a method within that controller from another class. How can I get a handle of the new scene controller?

public void startNewScene() throws IOException{
     Stage stage = new Stage();
     Partent root;
     root = FXMLLoader.load(getClass().getResource("fxmlfile.fxml");
     Scene scene = new Scene(root);
     Stage.setScene(scene);
     stage.show();

}

Solution

  • Create an FXMLLoader instance (instead of using the static load(...) method), and get the controller from it:

    public void startNewScene() throws IOException{
        Stage stage = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("fxmlfile.fxml"));
        Parent root = loader.load();
        MyController controller = loader.getController();
        Scene scene = new Scene(root);
        Stage.setScene(scene);
        stage.show();
    }
    

    Obviously replace MyController with the actual class name of the controller for fxmlfile.fxml.