I'm trying to display an alert dialog box when the player wins the game that I created. However, I get an exception:
java.lang.IllegalStateException: showAndWait is not allowed during animation or layout processing
I tried adding stop() in the AnimationTimer but it didn't work, still threw the same exception:
if (ball.getBall().getCenterY() == 0) {
//computer lost!
stop();
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(null);
alert.setHeaderText(null);
alert.setContentText("Good game. You won! Click OK to exit.");
alert.showAndWait(); //exception thrown here
System.exit(0);
}
You can only call showAndWait() in an event handler, not from within an animation. This is not explicitly documented in the Alert class, though it is documented in the documentation for Stage.
Call show() instead, and use a handler for the onHidden event for the alert to invoke something when the alert is closed:
if (ball.getBall().getCenterY() == 0) {
//computer lost!
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(null);
alert.setHeaderText(null);
alert.setContentText("Good game. You won! Click OK to exit.");
alert.setOnHidden(evt -> Platform.exit());
alert.show();
}
An alternative is to put your code into a private method and call using a method reference or lambda runnable in a Platform.runLater() call.
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(null);
alert.setHeaderText(null);
alert.setContentText("Good game. You won! Click OK to exit.");
alert.showAndWait(); //exception thrown here
System.exit(0);
This make the dialog pop up outside of a timer cycle and should fix the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With