我有一个相当简单的 JavaFX GUI 应用程序 https://dl.dropboxusercontent.com/u/34696560/KoBSON/PDFDownloader/layout_normal.jpg它有一个标签,显示距离某个操作开始还剩多少时间。为了实现这一点,我创建了一个 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 在这里看到 https://dl.dropboxusercontent.com/u/34696560/KoBSON/PDFDownloader/timer.jpg.
我读过关于调度线程池执行器 http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html and Java Timer 与 ExecutorService https://stackoverflow.com/questions/409932/java-timer-vs-executorservice/,但我很好奇这是否可以使用两个单独的计时器和计时器任务来完成。任何帮助和/或提示将不胜感激。