SwingWorker does not update JProgressBar without Thread.sleep() in custom dialog panel

The setProgress() API notes: “For performance purposes all these invocations are coalesced into one invocation with the last invocation argument only.” Adding Thread.sleep(1) simply defers the coalescence; invoking println() introduces a comparable delay. Take heart that your file system is so fast; I would be reluctant to introduce an artificial delay. As a concrete example that illustrates the effect, I added intermediate reporting to this complete example, as shown below.

private static class LogWorker extends SwingWorker<TableModel, String> {
    private long fileLength;
    private long bytesRead;
    ...
    this.fileLength = file.length();
    ...
    while ((s = br.readLine()) != null) {
        publish(s);
        bytesRead += s.length();
        int progress = (int)(100 * bytesRead / fileLength);
        // System.out.println(progress);
        setProgress(progress);
    }
    ...
}

lw.addPropertyChangeListener((PropertyChangeEvent e) -> {
    if ("progress".equals(e.getPropertyName())) {
        jpb.setValue((Integer)e.getNewValue());
    }
    if ("state".equals(e.getPropertyName())) {
        SwingWorker.StateValue s = (SwingWorker.StateValue) e.getNewValue();
        if (s.equals(SwingWorker.StateValue.DONE)) {
            jpb.setValue(100);
        }
    }
});

Leave a Comment