How to close a scene after a certain time JavaFX

I am currently working with two controller classes.

In Controller1, he creates a new stage that opens on top of the main one.

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

Now that this stage is open, I want it to remain open for about 5 seconds before closing.

Inside Controller2, I tried to implement something like

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

but I have no idea what to put inside the while loop to close it. I tried all kinds and nothing works.

+6
source share
3 answers

Use PauseTransition :

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

Carrying out your path, this will work:

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

You need to save your scene in a variable. It might be better to run this in a thread so that you can do something in 5 seconds. Another way is to run Thread.sleep (5000); and it will also be more efficient than a while loop.

0
source

This code sets the text of the TextArea element and makes it visible for a certain amount of time. It essentially creates a popup system message:

 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(); } 

This solution is completely general. You can change the setStyle methods to whatever code you want. You can open and close the scene if you want.

0
source

Source: https://habr.com/ru/post/979225/


All Articles