如何在一定时间后关闭JavaFX舞台

10

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

在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循环内部要放什么才能结束它。我尝试了各种方法,但都没有成功。

3个回答

27

使用PauseTransition

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

0
这段代码设置了 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方法更改为任何您想要的代码。如果您喜欢,您可以打开和关闭一个舞台。


0

按照你的方式,这将起作用:

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

while (mTime < end) 
{
    mTime = System.currentTimeMilis();
} 
stage.close();

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

4
如果您使用这些技术,您必须在线程中运行它,否则舞台的内容将无法显示。此外,您需要使用Platform.runLater(...)stage.close()包装起来,因为它必须在FX应用程序线程上执行。使用PauseTransition更容易些。 - James_D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接