【问题标题】:JavaFX 2 Window.hide after a specific timeJavaFX 2 Window.hide 在特定时间后
【发布时间】:2014-01-17 11:24:53
【问题描述】:

我想在 30 秒后关闭/隐藏窗口(或其他 特定的时间)。我用这段代码试了一下:

Calendar cal = Calendar.getInstance();
cal.getTime().getTime();

但我真的不知道如何让它工作。我正在使用 JavaFX 2。如何在使用 window.hide() 隐藏窗口之前指定等待的时间?

【问题讨论】:

    标签: java window javafx-2


    【解决方案1】:

    使用 PauseTransition 很简单,因为它将所有内容都保留在 JavaFX 应用程序线程上,您无需担心潜在的线程问题。

    如果您使用的是 Java 8:

    final Window window = new Stage();
    . . .
    PauseTransition pause = new PauseTransition(Duration.seconds(30));
    pause.setOnFinished(e -> window.hide());
    pause.play();
    

    或者,如果您使用的是 Java 7,请将 lambda 替换为:

    pause.setOnFinished(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            window.hide();
        }
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用 ScheduledExecutorService 来安排事件,尽管在 Java 8+ 上应该首选其他答案:

      ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
      scheduler.schedule(
           new Runnable() {
             @Override public void run() {
               Platform.runLater(new Runnable() {
                 @OVerride public void run() { stage.hide(); }
               })
             }
           }, 30, TimeUnit.SECONDS);
      

      【讨论】:

      • 请使用Platform.runLater()在GUI线程上执行。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 2018-08-28
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多