1

I use the below code to open a javafx fxml file in a different window on a button click event and it works fine. But if I click the same button again while the window opened it will create a duplicate window. Is there a possibly solutions to overcome this problem? Thanks in advance.

Parent parent = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Stage stage = new Stage(StageStyle.DECORATED);
stage.setTitle("Title");

stage.setScene(new Scene(parent));
stage.show();
1
  • What do you want it to do instead? You are explicitly creating a new window in this code... Commented May 4, 2017 at 17:09

1 Answer 1

1

I just stumbled upon this old question and figured I might answer it for anyone new to JavaFX or coding in general (I'm bored..).

In the provided code (see below) a new Stage is created every time, meaning that if this is run inside of a method you actually create a new Stage variable every time that the code is run:

Stage stage = new Stage(StageStyle.DECORATED);

What you could do instead create your Stage variable outside the method so that you either 1. just overwrite it every time or 2. have some "is showing" or a nullcheck or similar to see if a new stage should be created or if the existing one just needs to be shown.

For example:

private Stage stage;

private void onOpenNewStageBtnClicked(){
    if(stage == null){
        Parent parent = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        stage = new Stage(StageStyle.DECORATED);
        stage.setTitle("Title");
        stage.setScene(new Scene(parent));
    }
    stage.show();
}

Also, what I usually do is I create a Stage factory to avoid a lot of duplicate code and so that I can break out the creation of the stages and the loading of fxmls to other classes than my controller.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.