I have a JavaFx application in which I display an alert box using:
alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Title");
alert.setHeaderText("Some Text");
alert.setContentText("Choose your option.");
buttonTypeOne = new ButtonType("Yes");
buttonTypeCancel = new ButtonType("No", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeCancel);
Optional<ButtonType> result = alert.showAndWait();
Because the alert executesshowAndWait
, so it will be displayed till the user either presses 'Yes' or 'No' or 'Close' the dialog.
Problem: I need to close this dialog programatically from somewhere else. To elaborate, if, let's say the user does not chose any option for 20 sec, or let's say this alert box was shown for some background process which just got over, and now I wish to close this alert box by setting result
to be buttonTypeCancel
, instead of the user pressing any button.
(Like dispose
method in Swing)
How can I do this? I tried Event.fireevent (https://stackoverflow.com/a/22459308/3155986) but I am not able to write the correct event associated.
Thanks in advance!
Edit: Including sample code-
- MainApp.java - Java class responsible for handling the application
- Controller.java - Corresponding controller file
- Design.fxml - FXML file for the application which is loaded via MainApp.java and controlled by Controller.java
Compute.java - Another java class to perform computations.
public class Compute{ Alert alert;
public void function1{ Platform.runLater(new Runnable(){ public void run(){ alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Title"); alert.setHeaderText("Some Text"); alert.setContentText("Choose your option."); buttonTypeOne = new ButtonType("Yes"); buttonTypeCancel = new ButtonType("No", ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeCancel); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeOne){ // ... user chose "One" } else { // ... user chose CANCEL or closed the dialog } } }); } public void function2{ //......Does some long computation here //.... If the computation finishes before the user chooses 'Yes' or 'No' on alert box //...Then close the alertbox here and execute the code corresponding to buttonTypeCancel //..I tried alert.close(); and alert.hide(); but doesn't work. }
}
Also, is there any alternate solution to do this? Originally, I wanted to keep the Compute.java
clean of any javafx code but couldn't figure out how.
Try this
Or for more general
Full example: