JavaFX UI在新线程中执行任务时冻结 [英] JavaFX UI Frozen when performing Task in new Thread

查看:273
本文介绍了JavaFX UI在新线程中执行任务时冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在执行后台任务时让JavaFX UI保持活动状态时遇到问题。
我设置了这个非常简单的代码 -

I have a problem getting the JavaFX UI to keep active while performing a background Task. I have set up this very simple code -

@FXML
ProgressBar prgbProgress;

@FXML
private void onClick(ActionEvent event) {
      Task <Void> t = new Task <Void> () {

        @Override
        protected Void call() throws Exception {
          for (int i = 0; i < 10; i++) {
            updateProgress(i, 9);
            Thread.sleep(1000);
          }
          return null;
        }
      };
      prgbProgress.progressProperty().bind(t.progressProperty());
      new Thread(t).run();
}

我期望发生的是每隔~1秒更新一次进度条直到任务完成。相反,UI完全冻结10秒钟,之后进度条显示完成。
只是为了说清楚 - 问题不仅是所有更新最终都出现在一起,而且在此之前UI完全没有响应。

What I expect to happen is to have the progress bar update every ~1 second until the task is complete. Instead, the UI completely freezes for 10 seconds, after which the progress bar appears completed. Just to make it clear - the problem isn't only that all of the updates appear at once in the end, but also that the UI is completely unresponsive until then.

我已经阅读了关于这个主题的任何其他问题,但找不到答案。我做错了什么?

I have read just about any other question about this topic, but can't find an answer. What am I doing wrong?

谢谢。

推荐答案

使用 start()而不是 run()

@FXML
ProgressBar prgbProgress;

@FXML
private void onClick(ActionEvent event) {
      Task <Void> t = new Task <Void> () {

        @Override
        protected Void call() throws Exception {
          for (int i = 0; i < 10; i++) {
            updateProgress(i, 9);
            Thread.sleep(1000);
          }
          return null;
        }
      };
      prgbProgress.progressProperty().bind(t.progressProperty());
      //new Thread(t).run(); // wrong
      new Thread(t).start(); // right
}

这篇关于JavaFX UI在新线程中执行任务时冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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