How to return value from a stage before closing it?

前端 未结 4 654
遥遥无期
遥遥无期 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:06

    In my main controller I create Stage. Load controller which I can use like any class. And by creating an event I can get data just before closing the window.

    try {
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().getResource("/package/mySceneBuilderWindow.fxml"));
            final Pane rootPane = (Pane)loader.load();
            Scene scene =  new Scene(rootPane);
    
            Stage stage = new Stage();
            stage.setTitle("Optional title");
            stage.setScene(scene);
    
            mySceneBuilderWindowController controller = loader.getController();
            controller.iCanSendDataToCtrl("String for now"); // sending data or init textFields...
    
            stage.show();
    
            /* set event which is fired on close
                // How to close in the other window... (pressing X is OK too)
                    @FXML private Button fxidSave = new Button(); // global var
                    @FXML private void handleSaveButton() {
                        Stage stage = (Stage) fxidSave.getScene().getWindow();
                        stage.close(); // closes window
                    }
             */
            stage.setOnCloseRequest((EventHandler) new EventHandler() {
                public void handle(WindowEvent we) {
                    String iCanGetDataBeforeClose = controller.getData();
                    System.out.println(iCanGetDataBeforeClose);
                    // static class can be used aswell -> System.out.println(Context.getMyString());
                }
            });
    
        } catch (IOException e) {
            System.out.println("something wrong with .fxml - name wrong? path wrong? building error?");
        }  
    

    My other mySceneBuilderWindowController methods:

     public void iCanSendDataToCtrl(String giveMe) {
        // do something ex. myTextBox.setText(giveMe);
     }
     public String iCanGetDataBeforeClose() {
        // do something ex. return myTextBox.getText();
     }
    

提交回复
热议问题