javaFX 可控制自动关闭时间的弹出提示窗口

时间:2022-09-04 14:04:15


 
	public static void showTimedDialog(long time, String message) {
		Stage popup = new Stage();
		popup.setAlwaysOnTop(true);
		popup.initModality(Modality.APPLICATION_MODAL);
		Button closeBtn = new Button("知道了");
		closeBtn.setOnAction(e -> {
			popup.close();
		});
		VBox root = new VBox();
		root.setPadding(new Insets(20));
		root.setAlignment(Pos.BASELINE_CENTER);
		root.setSpacing(20);
		root.getChildren().addAll(new Label(message), closeBtn);
		Scene scene = new Scene(root);
		popup.setScene(scene);
		popup.setTitle("提示信息");
		popup.show();

		Thread thread = new Thread(() -> {
			try {
				Thread.sleep(time);
				if (popup.isShowing()) {
					Platform.runLater(() -> popup.close());
				}
			} catch (Exception exp) {
				exp.printStackTrace();
			}
		});
		thread.setDaemon(true);
		thread.start();
	}