[英]How to close a stage after a certain amount of time 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();
您需要將舞台保存到變量中。 也許最好在線程中運行它,以便您可以在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方法更改為所需的任何代碼。 您可以根據需要打開和關閉舞台。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.