prov
prov

Reputation: 61

How to create a dialog window after countdown/timer in java?

I would like to have an open dialog window every "n" seconds. I tried to use "Timer". I had the following error:

"Exception in threadTimer-0" java.lang.IllegalStateException: Not on FX application thread; 
currentThread = Timer-0"

from this I understood that I can not create other windows on threads that is not the javaFX thread.

private Integer animationTime;
private void routine(Integer time) throws Exception{
    animationTime = time;
    Timer timer = new Timer();
    timeline = new Timeline (new KeyFrame (Duration.seconds(1), evt -> 
    updateAnimation(time)) );
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.play();

    timer.schedule(new TimerTask() {// repeat over and over 
        @Override
        public void run() {
            alert= new Alert(Alert.AlertType.WARNING);
            alert.setTitle("Alert title");
            alert.setHeaderText("Alert...");
            alert.setContentText("....");
            alert.show();
            Optional<ButtonType> result = alert.showAndWait();
            if(result.get() == ButtonType.OK ){
                try {
                    routine(time);
                }
                catch (Exception e){}
            }
        }
    }, time*1000, time*1000);
}

private void updateAnimation(Integer time){
    if(animationTime.equals(0)){
         timeline.stop();
    }
    textTime.setText("Minutes: " + animationTime.toString());
    animationTime -= 1;
}

How can I fix it?

Update 30/12/2018

There is a new bug

timeline.setOnFinished((e)->{

         Alert alert= new Alert(Alert.AlertType.WARNING);
         alert.setTitle("Alert title");
         alert.setHeaderText("Alert...");
         alert.setContentText("....");
         alert.show();
         Optional<ButtonType> result = alert.showAndWait();
         if(result.get() == ButtonType.OK ){
                try {
                    routine(time);
                }
                catch (Exception ex){}
          }
}
     Optional<ButtonType> result = alert.showAndWait();

Exception in thread "JavaFX Application Thread" java.lang.IllegalStateException: showAndWait is not allowed during animation or layout processing

Upvotes: 2

Views: 789

Answers (1)

c0der
c0der

Reputation: 18792

No need to use Timer. Use Timeline#setOnFinished method:

timeline.setOnFinished((e)->{

         Alert alert= new Alert(Alert.AlertType.WARNING);
         alert.setTitle("Alert title");
         alert.setHeaderText("Alert...");
         alert.setContentText("....");
         alert.show();
         Optional<ButtonType> result = alert.showAndWait();
         if(result.get() == ButtonType.OK ){
                try {
                    routine(time);
                }
                catch (Exception ex){}
          }
 });

Upvotes: 0

Related Questions