【问题标题】:How to change UI from other threads如何从其他线程更改 UI
【发布时间】:2016-03-14 06:31:43
【问题描述】:

我想在其他线程中更改 UI 并尝试过这种方式-

SwingUtilities.invokeLater(new Runnable() {
        public void run() {

            try {
                Thread.sleep(5000);
                 lblToast.setText(6+"");
            } catch (InterruptedException ex) {
                Logger.getLogger(FXMLDocumentController.class.getName())
                                                  .log(Level.SEVERE, null, ex);
            }
        }
 });

但是这段代码不起作用。

【问题讨论】:

标签: java javafx


【解决方案1】:

在 JavaFX 应用程序线程上运行某些东西的基本工具是Platform.runLater()。但是,通过您的 cmets,您似乎还想在延迟后在 JavaFX 应用程序线程上运行某些东西,所以这就是这个答案所要解决的问题。


以下代码将安排在 5 秒延迟后在 JavaFX 应用程序线程上执行某些操作:

Platform.runLater(() -> {
    PauseTransition pause = new PauseTransition(Duration.seconds(5));
    pause.setOnFinished(event -> doSomething());
    pause.play();
});

在你的情况下, doSomething() 是:

lblToast.setText(6+"");

这类似于以下解决方案:

与使用 ScheduledExecutorService 相比,PauseTransition 的一个(次要)优势是转换不需要额外的线程。一个缺点是 ScheduledExecutorService 返回一个 ScheduledFuture ,这可能会让您对流程有更多的控制,因为您可以在 ScheduledFuture 上调用诸如 cancel() 或 isDone() 之类的方法(尽管额外的控制对您的应用程序可能并不重要)。

【讨论】:

  • @saman1046 Jewelsea 关于他的解决方案的优势是正确的。此外,我怀疑您不需要像我的解决方案中那样由ScheduledFuture 提供的控制,所以只需坚持他的解决方案(更简单)。 :-)
【解决方案2】:

ScheduledExecutorService.schedule() 允许在指定延迟后执行任务。 Platform.runLater() 在 JavaFX 线程上执行 Runnable

ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
Runnable setLabelOnUI = () -> Platform.runLater(() -> lblToast.setText(6+""));
ex.schedule(setLabelOnUI, 5000, TimeUnit.MILLISECONDS);

【讨论】:

  • 指定时间后
  • @saman1046 我更新了我的答案以指定执行前的延迟。
【解决方案3】:

编辑:确保标签变量是静态的,以便可运行线程可以访问它! 语法如下:

Runnable displayRunnable = new Runnable(){
                        @Override
                        public void run(){
                        //Enter Code to Change UI here!

                        }
 };
//Display Runnable allows us to modify UI components
Display.getDefault().syncExec(displayRunnable);

【讨论】:

  • 如果遇到非法线程异常,调用 Display.getDefault().syncExec(Runnable r);是要走的路。我相信您的问题涉及插入计时器。只需在函数 run 中插入计时器代码块即可。
  • 什么是显示类?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-07
相关资源
最近更新 更多