如何在Java中倒数/计时器后创建对话框窗口?

时间:2018-12-29 20:35:30

标签: java javafx timer countdown

我想每隔“ n”秒打开一个对话窗口。 我尝试使用“计时器”。我遇到以下错误:

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

据此我了解到,我不能在非javaFX线程的线程上创建其他窗口。

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

我该如何解决?

  

更新30/12/2018

有一个新错误

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

线程“ JavaFX Application Thread”中的异常   java.lang.IllegalStateException:在执行期间不允许showAndWait   动画或布局处理

1 个答案:

答案 0 :(得分:0)

无需使用Timer。使用Timeline#setOnFinished方法:

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