Alexandre Cavalcante
Alexandre Cavalcante

Reputation: 325

Setting a JProgressBar

I'm using javax.swing to build the GUI for a little application. Everything is working fine, but I just a have a little doubt. I would like to use a JProgressBar to indicate that the process export is running. As the class Post itself implements Runnable, if call setIndeterminate() just after run(), it's executed even before export() is over, as Java put it in another Thread.

Does anyone have some idea how to solve it?

    this.jProgressBar2.setIndeterminate(true);
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {

            Post post = new Post();
            post.export();
        }
    });

    this.jProgressBar2.setIndeterminate(true);

Upvotes: 0

Views: 89

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

Your problem is that since post.export() is being run in a background thread (I assume) then your code does not block, and the code after the run method will be called immediately.

Suggestions:

  • Get rid of the SwingUtilities.invokeLater(new Runnable() { statement as the code is already running on the Swing event thread and so this does nothing.
  • You need some notification mechanism for when post is done exporting. Give Post a SwingPropertyChangeSupport object, as well as an addPropertyChangeListener(...) method that allows outside classes (here the GUI) to add PropertyChangeListeners and use this with beans binding as well as PropertyChangeListeners to notify the GUI when the processing is done. This is done by calling the appropriate firePropertyChange(...) on the support object when the export is done.

Upvotes: 4

Related Questions