【问题标题】:How to close a stage after a certain amount of time JavaFX如何在一定时间后关闭一个阶段JavaFX
【发布时间】:2015-02-04 17:15:28
【问题描述】:

我目前正在使用两个控制器类。

在 Controller1 中,它创建了一个在主阶段之上打开的新阶段。

Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("Controller2.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();

现在一旦那个阶段打开,我希望它在关闭之前保持打开状态大约 5 秒。

在 Controller2 中,我尝试过实现类似

long mTime = System.currentTimeMillis();
long end = mTime + 5000; // 5 seconds 

while (System.currentTimeMillis() > end) 
{
      //close this stage  
} 

但我不知道在 while 循环中放置什么来关闭它。我已经尝试了各种方法,但没有任何效果。

【问题讨论】:

    标签: java while-loop javafx stage


    【解决方案1】:

    使用PauseTransition

    PauseTransition delay = new PauseTransition(Duration.seconds(5));
    delay.setOnFinished( event -> stage.close() );
    delay.play();
    

    【讨论】:

      【解决方案2】:

      按照你的方式做,这会奏效:

      long mTime = System.currentTimeMillis();
      long end = mTime + 5000; // 5 seconds 
      
      while (mTime < end) 
      {
          mTime = System.currentTimeMilis();
      } 
      stage.close();
      

      您需要将阶段保存到变量中。 也许最好在一个线程中运行它,这样你就可以在 5 秒内做一些事情。 另一种方法是运行 Thread.sleep(5000);这也将比 while 循环更高效。

      【讨论】:

      • 如果您使用这些技术,您将必须在线程中运行它,否则舞台的内容将不会显示。此外,您必须将 stage.close() 包装在 Platform.runLater(...) 中,因为它必须在 FX 应用程序线程上执行。使用PauseTransition 更容易。
      【解决方案3】:

      此代码设置 TextArea 元素的文本并使其在一定时间内可见。它本质上是创建一个弹出系统消息:

      public static TextArea message_text=new TextArea();
      
      final static String message_text_style="-fx-border-width: 5px;-fx-border-radius: 10px;-fx-border-style: solid;-fx-border-color: #ff7f7f;";
      
      public static int timer;
      public static void system_message(String what,int set_timer)
      {
      
          timer=set_timer;
      
          message_text.setText(what);
          message_text.setStyle("-fx-opacity: 1;"+message_text_style);
      
          Thread system_message_thread=new Thread(new Runnable()
          {
      
              public void run()
              {
      
                  try
                  {
                      Thread.sleep(timer);
                  }
                  catch(InterruptedException ex)
                  {
      
                  }
      
                  Platform.runLater(new Runnable()
                  {
      
                      public void run()
                      {
      
                          message_text.setStyle("-fx-opacity: 0;"+message_text_style);
      
                      }   
      
                  });
      
              }   
      
          });
      
          system_message_thread.start();
      
      }
      

      这个解决方案是完全通用的。您可以将 setStyle 方法更改为您想要的任何代码。您可以根据需要打开和关闭舞台。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-29
        • 2014-04-21
        • 1970-01-01
        • 2015-08-03
        • 2015-06-13
        • 2014-08-20
        • 1970-01-01
        相关资源
        最近更新 更多