如何在一定时间后关闭一个阶段JavaFX

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

在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循环中放入什么来关闭它。 我已经尝试过所有种类,但没有任何作用。

使用PauseTransition

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

按照自己的方式行事,这样可行:

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

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

此代码设置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方法更改为您想要的任何代码。 如果您愿意,可以打开和关闭舞台。