如何从我自己的Thread安全地修改JavaFX GUI节点? [英] How do I safely modify JavaFX GUI nodes from my own Thread?

查看:129
本文介绍了如何从我自己的Thread安全地修改JavaFX GUI节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试更改线程中的JavaFX GUI节点,但是我看到以下错误:

I try to change a JavaFX GUI node in a thread, but I see the following error:


线程中的异常Thread- 8java.lang.IllegalStateException:不在
FX应用程序线程; currentThread = Thread-8

Exception in thread "Thread-8" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-8

产生错误的示例代码:

public class Controller { 
  public Label label = new Label();

  public void load() {
    MyThread myThread = new MyThread();
    myThread.start();
  }

  public class MyThread extends Thread {
    public void run() {
      ......
      label.setText(""); // IllegalStateException: Not on FX application thread
    }
  }
}


推荐答案

活动场景图中JavaFX节点的所有操作必须在JavaFX应用程序线程上运行,否则您的程序可能无法正常工作。

All manipulations of JavaFX nodes in an active scene graph must run on the JavaFX application thread, otherwise your program may not work correctly.

当您尝试从JavaFX应用程序线程修改场景图节点的属性时,JavaFX将抛出异常 IllegalStateException:不在FX应用程序线程上。即使您没有获得IllegalStateException,也不应该从JavaFX应用程序线程修改场景图节点,因为如果您这样做,您的代码可能会无法预测地失败。

JavaFX will throw the exception IllegalStateException: Not on FX application thread when you try to modify attributes of scene graph nodes off of the JavaFX application thread. Even if you don't get an IllegalStateException, you should not be modifying scene graph nodes off of the JavaFX application thread because if you do your code may fail unpredictably.

Platform.runLater 调用允许JavaFX系统在JavaFX应用程序线程上运行代码。

Wrap code which manipulates scene graph nodes in Platform.runLater calls to allow the JavaFX system to run the code on the JavaFX application thread.

例如,您可以使用以下代码修复示例程序:

For example, you can fix your sample program with the following code:

Platform.runLater(new Runnable() {
  @Override public void run() {
    label.setText("");                       
  }
}

这篇关于如何从我自己的Thread安全地修改JavaFX GUI节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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