【问题标题】:TextArea is not updating while zip extraction压缩提取时 TextArea 未更新
【发布时间】:2017-04-10 05:46:15
【问题描述】:

我正在开发一个 JavaFx 应用程序,我有一个脚本可以提取 zip,然后执行一些其他操作,例如更新文件等。

我想要一个 textArea 来显示背景中发生的事情,例如“Zip 提取...”、“更新 xyz 文件”等。

到目前为止,我已经尝试过以下方式:

            MyTask<String> task;
                task = new MyTask<String>() {
                    @Override
                    protected String call() throws Exception {

                        File path = new File(exportTo.getAbsolutePath());
                        updateMessage("Extracting modular app to target directory...");
                        patcher.unZip(appPath.getAbsolutePath(), path.getAbsolutePath());

                        if (path.exists()) {
                            AppInfo info = getAppInfo();
                            patcher.patchAndroid(info, resourceZip, new File(path.getAbsolutePath() + "/" + appPath.getName().substring(0, appPath.getName().lastIndexOf("."))), this);
                            showOkAlert("Build completed!");
                        } else {
                            showOkAlert("Modular app folder not found");
                        }
                        return "";
                    }

                    @Override
                    protected void updateProgress(double workDone, double max) {
                        patcher.reportLogs(message);
                    }

                    private String message;

                    @Override
                    public void updateMessage(final String message) {

                        Platform.runLater(() -> patcher.reportLogs(message));

                        this.message = message;
                        //updateProgress(0, 0);
                    }
                };
                task.run();

MyTask 类

abstract class MyTask<T> extends Task<T> {

    abstract public void updateMessage(String message);
}

我尝试使用 updateProgress 方法 Platform.runLater() 但没有任何效果。

我在textArea中打印的所有消息都是在所有操作完成后打印出来的。

请帮忙。

【问题讨论】:

  • 你需要在一个新线程上运行你的Task,参见例如docs.oracle.com/javase/8/javafx/interoperability-tutorial/…
  • @sillyfly 非常感谢。解决了我的问题。
  • 那就考虑删除你的问题...
  • @GhostCat 我知道你为什么担心这个。但是如果其他人遇到这个问题怎么办?我花了很多时间找出问题所在,最后我不得不发布这个问题。我没有发布这个问题来获得支持。我希望你能理解。自从上个树日以来,我才刚刚开始使用 JavaFX。
  • 我明白了;但不是 JavaFx 专家,我的第一个想法是:这里的线程有问题......当然,你可以选择保留这个问题,但是我会建议 A)你稍微改进一下你的问题,比如把一个真正的minimal reproducible example 在那里......你或@sillyfly 提出了一个答案,并提供了针对该问题的工作代码。完成后请随时给我留言;我从不介意支持好的内容;-)

标签: multithreading javafx task


【解决方案1】:

作为Task 的javadoc 状态,您需要手动创建一个Thread 来执行您的Task

     Thread th = new Thread(task);
     th.start();

目前您的 task 正在应用程序 UI 线程上运行并阻止 UI 更新。

【讨论】:

    猜你喜欢
    • 2016-04-22
    • 2011-03-26
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 2012-11-20
    相关资源
    最近更新 更多