gpt4 book ai didi

java - TimerTask 无法更新 JavaFX 标签文本

转载 作者:行者123 更新时间:2023-12-03 23:00:45 26 4
gpt4 key购买 nike

我有一个 fairly simple JavaFX GUI application它有一个标签,显示在某个 Action 开始之前还剩下多少时间。为此,我创建了一个 DownloadTimer 类,如下所示:

public class DownloadTimer(){
private int minutes;
private int seconds;
private Timer innerTimer = new Timer();
private TimerTask innerTask;
private boolean isActive;

public DownloadTimer(int minutes, int seconds) {
if (seconds > 60) {
int minToAdd = seconds / 60;
this.minutes = minutes;
this.minutes += minToAdd;
this.seconds = seconds % 60;
} else {
this.minutes = minutes;
this.seconds = seconds;
}
}

public void start() {
innerTask = new TimerTask() {
@Override
public void run() {
isActive = true;
System.out.println(getTime());
if (seconds == 0 && minutes > 0){
minutes -= 1;
seconds = 59;
} else if (seconds == 0 && minutes == 0){
isActive = false;
innerTimer.cancel();
innerTimer.purge();
System.out.println("DownloadTimer DONE");
} else {
seconds -= 1;
}
}
};
innerTimer.scheduleAtFixedRate(innerTask, 0, 1000);
}
}

然后,我正在创建 DownloadTimer 对象并从我的 Main (JavaFX) 类开始倒计时:

/* 
code omitted for better readability
*/

downloadTimer = new DownloadTimer(0, 5);

// label gets the .getTime() value, which returns a formatted String like "00:05", "00:04", etc.
lblTimer.setText( downloadTimer.getTime() );

// start the countdown
downloadTimer.start();

// create a new timer which checks if the downloadTimer is still counting
final Timer timer = new Timer();
TimerTask timerTask = new TimerTask(){
@Override
public void run(){
if (downloadTimer.getIsActive() == false){
timer.cancel();
timer.purge();
System.out.println("GUI timer DONE");
} else {
// if it's still running, then continuously update the label's text
lblTimer.setText( downloadTimer.getTime() );
// this is where I get the error described below
}
}
};
// repeat after 1000ms
timer.scheduleAtFixedRate(timerTask, 0, 1000);

我遇到的问题是我无法使用主类中的 lblTimer.setText( downloadTimer.getTime() ); 设置标签文本,错误我'我得到的是 TimerThread.run() line: not available [local variables unavailable] as seen here .

我读过 ScheduledThreadPoolExecutorJava Timer vs ExecutorService ,但我很好奇这是否可以使用两个单独的计时器和 TimerTasks 来完成。任何帮助和/或提示将不胜感激。

最佳答案

我很惊讶你没有看到异常。要从单独的线程更新标签,需要安排更新在 FX 线程中运行:

Platform.runLater(new Runnable() {
public void run() {
lblTimer.setText(downloadTimer.getTime());
}
});

关于java - TimerTask 无法更新 JavaFX 标签文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20268593/

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