Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a stage after a certain amount of time JavaFX

I'm currently working with two controller classes.

In Controller1 it 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 once that stage is open, I want it to stay open for about 5 seconds before closing itself.

Within Controller2, I've tried implementing 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've tried all sorts and nothing works.

like image 312
Doja Avatar asked Dec 06 '14 17:12

Doja


People also ask

How do you close a JavaFX stage?

Be default, to quit the program is to let the user click the standard window close button, typically represented by an X in the upper-right corner of the window's title bar.

What does JavaFX stage stage do?

A Stage in JavaFX is a top-level container that hosts a Scene, which consists of visual elements. The Stage class in the javafx. stage package represents a stage in a JavaFX application. The primary stage is created by the platform and passed to the start(Stage s) method of the Application class.

Which JavaFX application lifecycle method the application shuts down?

Terminating the JavaFX Application When the last window of the application is closed, the JavaFX application is terminated implicitly. You can turn this behavior off bypassing the Boolean value “False” to the static method setImplicitExit() (should be called from a static context).


1 Answers

Use a PauseTransition:

PauseTransition delay = new PauseTransition(Duration.seconds(5));
delay.setOnFinished( event -> stage.close() );
delay.play();
like image 159
James_D Avatar answered Oct 08 '22 03:10

James_D