带有Label.setText的JavaFx2 IllegalStateException [英] JavaFx2 IllegalStateException with Label.setText

查看:62
本文介绍了带有Label.setText的JavaFx2 IllegalStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我使用像这样的简单线程:

Why when i use a simple Thread like this :

Thread t = new Thread(new Runnable() {
public void run(){
while(true){
  .....
 idLabel.setText(Date.toString);
 Thread.sleep(1000);`
}
t.start(); 

我遇到此错误:

java.lang.IllegalStateException:不在FX应用程序线程上; currentThread =线程4

java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4

但是如果我使用输入文本(例如idInputText)而不是标签,则没有错误?

but if i use an input text (like idInputText) and not a label i didn't have the error ??

推荐答案

JavaFX的所有UI操作都应在FX应用程序线程上执行.您正在创建一个新的Thread t,它不是FX应用程序线程.因此出现异常消息:

All UI operation for JavaFX should be performed on FX application thread. You are creating a new Thread t which is not a FX application thread. Hence the exception message:

java.lang.IllegalStateException:不在FX应用程序线程上; currentThread = Thread-4

java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4

您需要使用 Platform#runLater()方法进行此类操作,如下所示:

You need to use Platform#runLater() method for such operations, like as following:

while(true){
    .....
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            idLabel.setText(Date.toString);
        }
    });
    Thread.sleep(1000);`
}

这篇关于带有Label.setText的JavaFx2 IllegalStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆