Как создать диалоговое окно после обратного отсчета / таймера в Java? - PullRequest
0 голосов
/ 29 декабря 2018

Я хотел бы иметь открытое диалоговое окно каждые "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Поток "java.lang.IllegalStateException: showAndWait не допускается во время обработки анимации или макета

1 Ответ

0 голосов
/ 30 декабря 2018

Не нужно использовать Timer.Используйте Временную шкалу # 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){}
          }
 });
...