SwingWorker process() 不会为每个 publish() 调用

SwingWorker process() is not invoked for each publish()

我是 Swings 新手。

我在一个 txt 文件中有将近 200 万条记录,需要逐一读取(基于拆分列)并将它们推送到 Table。完成整个过程大约需要 4-5 秒。

我面临的问题:JTable/UI 正在等待所有 200 万条记录得到处理,然后一起显示。 是否有任何选项可以将记录推送到 JTable UI 基于批处理或并行推送,就像一旦我处理了 500 条记录,我可以将它们推送到 UI ?

尝试使用SwingWorker实现,每500条记录调用push()方法,但是process()只调用一次,不是每500条,如有错误请指正。

new SwingWorker<Boolean, java.util.List<String>>() {
    @Override
    protected Boolean doInBackground() throws Exception {

        // Example Loop
        int i = 1;
        String line;
        java.util.List<String> list = new LinkedList();
        while ((line = in.readLine()) != null) {
            line = line.trim().replaceAll(" +", " ");
            list.add(line);

            if (i % 500 == 0) {
                publish(list);
                list = new LinkedList();
            }
            i++;
        }

        return true;
    }

    @Override
    protected void process(java.util.List<java.util.List<String>> chunks) {
        dtm.addRow(new String[]{"data"});
        System.out.println("Found even number: " + chunks.size());
    }
}.execute();

谢谢。

Swing 可以自由地将对 publish 的多个调用关联到对 process 的单个调用,如文档所述:

publish

Because the process method is invoked asynchronously on the Event Dispatch Thread multiple invocations to the publish method might occur before the process method is executed. For performance purposes all these invocations are coalesced into one invocation with concatenated arguments. For example:

publish("1");
publish("2", "3");
publish("4", "5", "6");

might result in:

process("1", "2", "3", "4", "5", "6")

不需要每 500 次迭代发布一次,只要有一个结果可用就发布,让 Swing 按需要合并。