Dmitry Nelepov
Dmitry Nelepov

Reputation: 7306

JavaFX passing and getting parameters between Stage

I have two stages

Stage1 with Scene1 and own Controller1
and
Stage2 with another Scene2 and Controller2

From Stage1 i call Stage2 with ShowAndWait.
And set for Stage2 listener for Hiding stage.

From Stage2.Controller2 a call hide and breakpointed in

setOnHiding(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent t) {
                System.out.print(t.getSource());
            }
        });

How i can passing paramers between this stages in cases:
1. stage1 pass to stage2
2. stage2 result some data params to stage1

?

Upvotes: 0

Views: 4343

Answers (1)

yelliver
yelliver

Reputation: 5926

This is my solution: I have 2 class MyStage and MyController Stage1, Stage2 should extend MyStage Controller1, Controller2 should extend MyController

Stage2 s2 = new MyStage(data);
s2.show();
result = s2.getResult();

class Stage2 extends Stage{
    private FXMLLoader fxmlLoader;
    private Object data;
    private Object result;

    public Stage(Object data){
        this.data = data;
        ...//do something with data
        getController().initWithData(data);
    }

    Object getResult(){
        return getController().getResult();
    }

    public MyController getController() {
        return (MyController) fxmlLoader.getController();
    }
}

Class MyController{
    public void initWithData(Object data){
    ...//
    }

    public Object getResult(){
    ...//
    return result;
    }

    public void setStage(Stage stage) {
            this.stage = stage;
}

    @FXML
    protected void close() {
            getStage().close();
    }

}

it's general but there are some minor changes to the code when using fxml vs non-fxml. You can pass stage references to controller to close the stage from another controller. I am too sleepy now, hope there's no error. I will update later

Upvotes: 1

Related Questions