我有以下代码:
public class FXMLDocumentController implements Initializable{
@FXML
Label timer;
static int waitTime = 0;
@FXML
protected void beginSurfing(){
this.timer.setText("5");
waitTime = 5;
t = new Timer();
t.scheduleAtFixedRate(new TimerTask(){
@Override
public void run(){
setInterval();
setCounterText();
}
}, 1000, 1000);
}
private static int setInterval(){
if(waitTime == 1){
t.cancel();
}
return --waitTime;
}
public void setCounterText(){
this.timer.setText(String.valueOf(waitTime));
}
}
为什么我在setText()
方法中尝试setCounterText()
时出现错误,但是当我在beginSurfing()
中执行此操作时,我没有收到错误消息?这是抛出的异常......
Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:210)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:393)
at javafx.scene.Parent$2.onProposedChange(Parent.java:372)
at com.sun.javafx.collections.VetoableListDecorator.setAll(VetoableListDecorator.java:115)
at com.sun.javafx.collections.VetoableListDecorator.setAll(VetoableListDecorator.java:110)
at com.sun.javafx.scene.control.skin.LabeledSkinBase.updateChildren(LabeledSkinBase.java:635)
at com.sun.javafx.scene.control.skin.LabeledSkinBase.handleControlPropertyChanged(LabeledSkinBase.java:207)
at com.sun.javafx.scene.control.skin.LabelSkin.handleControlPropertyChanged(LabelSkin.java:52)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$2.call(BehaviorSkinBase.java:189)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$2.call(BehaviorSkinBase.java:187)
at com.sun.javafx.scene.control.MultiplePropertyChangeListenerHandler$1.changed(MultiplePropertyChangeListenerHandler.java:55)
at javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:89)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:176)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:80)
at javafx.beans.property.StringPropertyBase.fireValueChangedEvent(StringPropertyBase.java:103)
at javafx.beans.property.StringPropertyBase.markInvalid(StringPropertyBase.java:110)
at javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:143)
at javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:49)
at javafx.beans.property.StringProperty.setValue(StringProperty.java:65)
at javafx.scene.control.Labeled.setText(Labeled.java:151)
at testbrowser.FXMLDocumentController.setCounterText(FXMLDocumentController.java:92)
at testbrowser.FXMLDocumentController$1.run(FXMLDocumentController.java:78)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
答案 0 :(得分:2)
我知道了,我需要在FX上运行它,为了解决这个问题,我使用了Platform.runLater()
修复了我的问题。
t.scheduleAtFixedRate(new TimerTask(){
@Override
public void run(){
Platform.runLater(new Runnable(){
public void run(){
setInterval();
setCounterText();
}
});
}
}, 1000, 1000);