Question

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();
Was it helpful?

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().

OTHER TIPS

Your code as it is right now, invokes the invokeLater only after the writer has returned. This is because the invokeLater is in the same thread as the actual work, so both statements will be executed sequentially. What you need to do is to schedule progress bar updates from within the writer. If you don't want to clutter the writer with interface-updating logic, consider using Observer pattern.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top