我是这里的新人:)
我有一个关于 JavaFX 绑定的小问题。我创建了作为时钟工作的 Task 并返回必须在特殊标签(label_Time)中设置的值。此标签显示玩家在测验中的答案还剩多少秒。
问题是如何使用计时器任务自动更改标签中的值?我试图以这种方式将计时器任务(秒)中的值链接到 label_Time 值......
label_Time.textProperty().bind(timer.getSeconds());
...但它不起作用。有什么办法可以做这件事吗?
提前感谢您的回答!:)
Controller类中的初始化方法:
public void initialize(URL url, ResourceBundle rb) {
Timer2 timer = new Timer2();
label_Time.textProperty().bind(timer.getSeconds());
new Thread(timer).start();
}
任务类“Timer2”:
public class Timer2 extends Task{
private static final int SLEEP_TIME = 1000;
private static int sec;
private StringProperty seconds;
public Timer2(){
Timer2.sec = 180;
this.seconds = new SimpleStringProperty("180");
}
@Override protected StringProperty call() throws Exception {
int iterations;
for (iterations = 0; iterations < 1000; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
System.out.println("TIK! " + sec);
seconds.setValue(String.valueOf(sec));
System.out.println("TAK! " + seconds.getValue());
// From the counter we subtract one second
sec--;
//Block the thread for a short time, but be sure
//to check the InterruptedException for cancellation
try {
Thread.sleep(10);
} catch (InterruptedException interrupted) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
}
}
return seconds;
}
public StringProperty getSeconds(){
return this.seconds;
}
}