How to access a JavaFx Stage from a Controller?

后端 未结 2 2006
半阙折子戏
半阙折子戏 2020-12-19 06:37

I\'m converting a pure JavaFx app, in which the code below worked fine when put all in one class, to a FXML one, where the Stage declaration and the button handler are in se

相关标签:
2条回答
  • 2020-12-19 06:54

    Another way is define a static getter for the Stage and Access it

    Main Class

    public class Main extends Application {
        private static Stage primaryStage; // **Declare static Stage**
    
        private void setPrimaryStage(Stage stage) {
            Main.primaryStage = stage;
        }
    
        static public Stage getPrimaryStage() {
            return Main.primaryStage;
        }
    
        @Override
        public void start(Stage primaryStage) throws Exception{
            setPrimaryStage(primaryStage); // **Set the Stage**
            Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
            primaryStage.setTitle("Hello World");
            primaryStage.setScene(new Scene(root, 300, 275));
            primaryStage.show();
        }
    }
    

    Now you Can access this stage by calling

    Main.getPrimaryStage()

    In Controller Class

    public class Controller {
    public void onMouseClickAction(ActionEvent e) {
        Stage s = Main.getPrimaryStage();
        s.close();
    }
    }
    
    0 讨论(0)
  • 2020-12-19 07:03

    In your situation, it is probably easiest to get the scene from the ActionEvent parameter of your handler:

    @FXML
    private void handleSourceBrowse(ActionEvent ae) {
        Node source = (Node) ae.getSource();
        Window theStage = source.getScene().getWindow();
    
        sourceDirectoryChooser.showDialog(theStage);
    }
    

    See JavaFX: How to get stage from controller during initialization? for some more information. I am not in favor of the highest rated answer though, since it adds a compile time dependency to the controller after the .fxml file has been loaded (after all that question was tagged with javafx-2, so not sure if the above approach already worked there, and also the context of the question looks a bit different).

    See also How do I open the JavaFX FileChooser from a controller class?

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