I have a JavaFx application in which I display an alert box using:
alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle(\"Title\");
alert.setHeaderText(
You can invoke close() method on the Alert or any Dialog.
Here is a simple example which waits for 5 secs, and if the Alert is still showing, it closes it.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.stage.Stage;
import java.util.Optional;
public class Main extends Application{
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Title");
alert.setHeaderText("Some Text");
alert.setContentText("Choose your option.");
ButtonType buttonTypeOne = new ButtonType("Yes");
ButtonType buttonTypeCancel = new ButtonType("No", ButtonBar.ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeCancel);
Thread thread = new Thread(() -> {
try {
// Wait for 5 secs
Thread.sleep(5000);
if (alert.isShowing()) {
Platform.runLater(() -> alert.close());
}
} catch (Exception exp) {
exp.printStackTrace();
}
});
thread.setDaemon(true);
thread.start();
Optional result = alert.showAndWait();
}
}