【发布时间】:2016-02-03 05:49:10
【问题描述】:
你好,我有这段代码可以用 javafx 显示图像
public void CantaCarta() throws InterruptedException {
startGame.setDisable(true);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
SwingUtilities.invokeLater(() -> {
for (int x=1; x<55;x++){
Image image = new Image(getClass().getResource("imgs/"+JuegoLoto.Muestra(x-1)+".jpg").toString(), true);
cantada.setImage(image);
if (x >= 54) {
System.out.print("Termina");
timer.cancel();
} else {
System.out.print(" "+x+" ");
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
}
}
}
});
}
}, 0, 1000);
}
图像会正确显示,但是当图像编号 54 在屏幕上时,它会循环回到 1,这都是因为
Thread.sleep(200);
我该如何解决这个问题?我想延迟图像之间的时间
【问题讨论】:
-
本质上,您正在使用循环和
Thread.sleep阻塞事件调度线程,这会阻止它更新屏幕。使用 SwingTimer(延迟 200 毫秒)或SwingWorker -
你弄清楚你在这里实际做什么了吗?您正在以固定速率安排任务,其中有一个循环,当 iit 完成时取消任务。所以这个任务实际上只运行一次。那么为什么是定时器呢?我建议您应该让计时器进行迭代。