gpt4 book ai didi

java - 如何在java中倒计时/计时器后创建一个对话框窗口?

转载 作者:太空宇宙 更新时间:2023-11-04 09:57:15 24 4
gpt4 key购买 nike

我希望每“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;
}

如何修复它?

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

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

最佳答案

无需使用计时器。使用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){}
}
});

关于java - 如何在java中倒计时/计时器后创建一个对话框窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53973156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com