Moe
Moe

Reputation: 1527

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

}

Upvotes: 0

Views: 411

Answers (1)

James_D
James_D

Reputation: 209330

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.

Upvotes: 2

Related Questions