1

How do I close a stage in JavaFX 2 after some specific external event has occurred? Suppose I have a stage with a simple progress bar that is filled up by a Task (borrowed from another answer):

Task<Void> task = new Task<Void>(){
                @Override
                public Void call(){
                    for (int i = 1; i < 10; i++)    {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(i);
                        updateProgress(i, 10);
                    }
                return null;                
                }
            };

How do I close the window automatically (and open the next one) after the Task is done and the ProgressBar is filled to 100%?

  • 2
    There is some general information on closing a stage in the related questions: [JavaFX 2.0: Closing a stage (window)](http://docs.oracle.com/javafx/2/api/javafx/application/Platform.html) and [JavaFX2 : Closing a stage (substage) from within itself](http://stackoverflow.com/questions/11468800/javafx2-closing-a-stage-substage-from-within-itself) – jewelsea Apr 24 '13 at 20:54

1 Answers1

3

Before return null; you can add

Platform.runLater(
    new Runnable() {
        public void run() {
            stage.close();
        }
    }
);

or

progressBar.progressProperty().addListener(new ChangeListener<Number>(){
//add checking, that progress is >= 1.0 - epsilon
//and call stage.close();
})

The first is better. But note, that task is done on a separate thread. so you should put a request on stage.close() on JFX thread using special call.

Also, jewelsea provides links on stage closing questions in comment to the question.

Alexander Kirov
  • 3,624
  • 1
  • 19
  • 23