Closing a Stage from within its controller

后端 未结 2 789
情话喂你
情话喂你 2020-12-17 19:04

I need a way to close a Stage from within itself by clicking a Button.

I have a main class from which I create the main stage with a scene.

相关标签:
2条回答
  • 2020-12-17 19:37

    You can derive the stage to be closed from the event passed to the event handler.

    new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent actionEvent) {
        // take some action
        ...
        // close the dialog.
        Node  source = (Node)  actionEvent.getSource(); 
        Stage stage  = (Stage) source.getScene().getWindow();
        stage.close();
      }
    }
    
    0 讨论(0)
  • 2020-12-17 19:37

    In JavaFX 2.1, you have few choices. The way like in jewelsea's answer or the way what you have done already or modified version of it like

    public class AboutBox extends Stage {
    
        public AboutBox() throws Exception {
            initModality(Modality.APPLICATION_MODAL);
            Button btn = new Button("Close");
            btn.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent arg0) {
                    close();
                }
            });
    
            // Load content via
            // EITHER
    
            Parent root = FXMLLoader.load(getClass().getResource("AboutPage.fxml"));
            setScene(new Scene(VBoxBuilder.create().children(root, btn).build()));
    
            // OR
    
            Scene aboutScene = new Scene(VBoxBuilder.create().children(new Text("About me"), btn).alignment(Pos.CENTER).padding(new Insets(10)).build());
            setScene(aboutScene);
    
            // If your about page is not so complex. no need FXML so its Controller class too.
        }
    }
    

    with usage like

    new AboutBox().show();
    

    in menu item action event handler.

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