How to call functions on the stage in JavaFX's controller file

后端 未结 6 1883
孤独总比滥情好
孤独总比滥情好 2021-01-02 05:08

I am using javafx along with fxml, so I use the controller for the real coding. I need to do a few operations on the stage, such as getting

6条回答
  •  星月不相逢
    2021-01-02 05:41

    The best approach is to create a new controller and pass the stage via the constructor (don't use fx:controller on FXML file), otherwise the stage will be null when initialize() is invoked (At that moment of time, when load() invokes initialize(), no stage is attached to the scene, hence the scene's stage is null).

    public class AppEntryPoint extends Application
    {
        private FXMLLoader loader;
    
        @Override
        public void init() throws Exception
        {
            loader = new FXMLLoader(getClass().getResource("path-to-fxml-file"));
        }
    
        @Override
        public void start(Stage initStage) throws Exception
        {
            MyController controller = new MyController(initStage);
            loader.setController(controller);
            Scene scene = loader.load();
            initStage.setScene(scene);
            initStage.show();
        }
    
        public static void main(String[] args)
        {
            launch(args);
        }
    }
    
    public class MyController
    {
        private Stage stage;
    
        @FXML private URL location;
        @FXML private ResourceBundle resources;
    
        public MyController(Stage stage)
        {
            this.stage = stage;
        }
    
        @FXML
        private void initialize()
        {
            // You have access to the stage right here
        }
    }
    

提交回复
热议问题