Search code examples
javajavafxuser-inputjoptionpane

How can I get make my program wait until JavaFX window has been closed before continuing?


I have a program that is displaying a barchart of results. I want to wait until the user closes the bar chart to continue to the next line of code which is asking if they want to enter new information for the chart.

Scene scene = BarGraph.getBarChart();
primaryStage.setScene(scene);
primaryStage.setTitle("Bar Chart");
primaryStage.show();

repeat = JOptionPane.showConfirmDialog(null, "Would you like to enter another number?");

What is happening is the scene for the bar chart will open, but nothing will be displayed and immediately JOptionPane pops up with the question. If I hit no, then the chart displays, but the program ends. If I hit yes, the program loops back to earlier dialog windows, but won't display the chart until the other dialog ends.

I want to wait to prompt the user until after they close the bar chart. I'm so frustrated at this point, that I'd even put an artificial pause like wait(5000) or something, though I have not been able to get that to work either.

I've read into this so much and have yet to find a solution that actually works. The closest question was this: JavaFX wait till stage has been closed

From what I read there is that I can't actually cause the program to wait, but can set actions to occur once the window is closed. But following the suggestions there just caused the stage to open and then immediately close. I've been down several other rabbit holes, but to no avail.


Solution

  • Try using Stage.showAndWait() instead of Stage.show().

    The show() method returns immediately regardless of the modality of the stage. Use the showAndWait() method if you need to block the caller until the modal stage is hidden (closed). The modality must be initialized before the stage is made visible.

    - JavaFX documentation for Stage

    As James_D points out, you'll need to create another stage first, as using this on the primary stage will cause an error.

    This method must not be called on the primary stage or on a stage that is already visible.