package id.co.gtc.erhacam; import javafx.animation.PauseTransition; import javafx.application.Platform; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.util.Duration; import java.util.Optional; public class AutoCloseAlert { private static Stage currentAlertStage; public static String shownTitle = ""; public static String shownContent = ""; public static String shownHeader = ""; private static void clear(){ shownTitle = ""; shownContent = ""; shownHeader = ""; } /** * Close the current alert if it is shown */ public static void close(){ Optional.ofNullable(currentAlertStage).ifPresent(Stage::close); currentAlertStage = null; clear(); } /** * Show an alert with a title, header, content, and automatically close after a few seconds * If called several times, the previous alert will be closed before showing a new one * @param title the title of the alert * @param header the header of the alert * @param content the content of the alert * @param seconds the number of seconds before the alert is closed, or put 0 to keep it open */ public static void show(String title, String header, String content, int seconds) { Platform.runLater(()->{ // close previous alert before showing a new one Optional.ofNullable(currentAlertStage).ifPresent(Stage::close); Stage alertStage = new Stage(); alertStage.initModality(Modality.APPLICATION_MODAL); alertStage.initStyle(StageStyle.UTILITY); alertStage.setAlwaysOnTop(true); alertStage.setResizable(false); double screenwidth = Screen.getPrimary().getVisualBounds().getWidth(); double width = screenwidth/4; double height = width * 9 / 16; Label headerLabel = new Label(header); headerLabel.setStyle("-fx-font-weight: bold; -fx-font-size: 16px;"); headerLabel.setMinHeight(height*0.25); Label contentLabel = new Label(content); contentLabel.setStyle("-fx-font-size: 12px;"); contentLabel.setMinHeight(height*0.75); VBox root = new VBox(10, headerLabel, contentLabel); root.setPrefSize(width, height); root.setAlignment(Pos.CENTER); Scene scene = new Scene(root); alertStage.setScene(scene); alertStage.setTitle(title); currentAlertStage = alertStage; alertStage.show(); shownHeader = header; shownContent = content; shownTitle = title; if (seconds>0){ PauseTransition delay = new PauseTransition(Duration.seconds(seconds)); delay.setOnFinished(e -> { alertStage.close(); if (currentAlertStage == alertStage) { currentAlertStage = null; } clear(); } ); delay.play(); } }); } }