How to return value from a stage before closing it?

前端 未结 4 650
遥遥无期
遥遥无期 2020-11-27 23:26

First of all, sorry for the bad english.

Here is the case:

I have a \"main stage\" where i press a button to open a \"second stage\" where i have a table, th

4条回答
  •  情歌与酒
    2020-11-28 00:19

    Here is a possible example. The structure is the same as in the answer in my comment.

    The second Stage is opened through a "controller" that is stores the data that should be returned even when the Stage is closed and exposes a getter to be used to retrieve the value from the outer world.

    import javafx.application.Application;
    import javafx.stage.Modality;
    import javafx.stage.Stage;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.VBox;
    
    
    public class Main extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            try {
                BorderPane root = new BorderPane();
                Scene scene = new Scene(root,400,400);
    
                Button bSecondStage = new Button("Show second Stage");
                bSecondStage.setOnAction(e -> {
                    WindowController wc = new WindowController();
                    wc.showStage();
                    System.out.println(wc.getData());
                });
    
                root.setCenter(bSecondStage);
    
    
                primaryStage.setScene(scene);
                primaryStage.show();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    
        class WindowController {
            private String data;
    
            void showStage() {
                Stage stage = new Stage();
                stage.initModality(Modality.APPLICATION_MODAL);
    
                VBox root = new VBox();
                Scene scene = new Scene(root);
                TextField tf = new TextField();
                Button submit = new Button("Submit");
    
                submit.setOnAction(e -> {
                    data = tf.getText();
                    stage.close();
                });
    
                root.getChildren().addAll(tf, submit);
                stage.setScene(scene);
                stage.showAndWait();
            }
    
            String getData() {
                return data;
            }
        }
    }
    

提交回复
热议问题