我试图从线程中设置文本对象的字符串,但是它给了我这个错误:
Exception in thread "Thread-4" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(Unknown Source)
at javafx.scene.Scene.addToDirtyList(Unknown Source)
at javafx.scene.Node.addToSceneDirtyList(Unknown Source)
at javafx.scene.Node.impl_markDirty(Unknown Source)
at javafx.scene.shape.Shape.impl_markDirty(Unknown Source)
at javafx.scene.Node.impl_geomChanged(Unknown Source)
at javafx.scene.text.Text.impl_geomChanged(Unknown Source)
at javafx.scene.text.Text.needsTextLayout(Unknown Source)
at javafx.scene.text.Text.needsFullTextLayout(Unknown Source)
at javafx.scene.text.Text.access$200(Unknown Source)
at javafx.scene.text.Text$2.invalidated(Unknown Source)
at javafx.beans.property.StringPropertyBase.markInvalid(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.scene.text.Text.setText(Unknown Source)
at uy.com.vincent.fx.handling.TableController$1.run(TableController.java:70)Handler类:
@FXML
private Text timer;
@Override
public void initialize(URL url, ResourceBundle rb) {
init();
new Thread() {
public void run() {
while(true) {
Calendar cal = new GregorianCalendar();
int hour = cal.get(cal.HOUR);
int minute = cal.get(cal.MINUTE);
int second = cal.get(cal.SECOND);
int AM_PM = cal.get(cal.AM_PM);
String time = hour + "" + minute + "" + second;
timer.setText(time);
}
}
}.start();
}我在跟踪a tutorial。本教程中的那个家伙没有使用JavaFX。
我试过使用Platform.runLater(),它确实工作,但它崩溃了我的程序。我还尝试在Platform.runLater(new Runnable() { })方法上创建一个计时器,但它给出的错误与以前相同。
发布于 2015-04-04 19:56:17
将timer.setText()包装在Platform.runLater()中。在它的外部,在while循环中,添加Thread.sleep(1000);
非法状态异常背后的原因是您试图在JavaFX应用程序线程以外的某个线程上更新UI。
您的应用程序在添加时崩溃的原因是通过添加要在UI线程上无限执行的进程来重载UI线程。让线程休眠1000 for将帮助您克服这个问题。
如果可能的话,用计时器或TimerTask替换while(true)。
有关更多选项,请参见this link
https://stackoverflow.com/questions/29449297
复制相似问题