Search code examples
javamultithreadingswinginvokelater

Updating a JProgressBar while doing a long comparison


I got a serious problem with my recent project: I am doing a long comparison in a methode called writer(...) and it takes about 20 seconds. The methode is decalred in the View class, where my GUI elements are setted also. While the method is comparing, I would like to update a progressbar, but anyway I do it, it's always getting updated when the methode has done it's comparison... Any ideas?

Here's my code (okay - parts of it):

    Thread t = new Thread(new Runnable()
{
    public void run()
    {
        writer(List1, List2);
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {

                bar.setValue(SOME_VALUE);
            }
        });
    }
});

The thread ist started through an ActionListener of an button with

t.start();

Solution

  • It gets updated in the end because that's where you update it. You need to do the bar.setValue() (in EDT, like you already correctly do), every time you need to update the bar.

    A cleaner approach, perhaps, is using a SwingWorker. Use publish() when the value has updated. SwingWorkers can coalesce multiple changes to one, and you can ignore all but the last one (like you likely want to do in your case) in process().