zaczap
zaczap

Reputation: 1396

Swing JProgressBar doesn't repaint as I'd expect it to

Hey all, I have a pretty simple problem someone should be able to help me with. All I want is a small frame with a progress bar that updates, right now it's not updating:

final JProgressBar bar = new JProgressBar(0,250000);
bar.setValue(1000);
bar.setIndeterminate(false);
JOptionPane j = new JOptionPane(bar);
final JDialog d = j.createDialog(j,"Expierment X");
d.pack();
d.setVisible(true);
bar.setValue(40000);

The 40,000 value doesn't show up, only the measly 1000. I'd prefer to not have to write any classes to handle repaint calls or whatever is involved in doing that (haven't used Swing in forever).

Thanks!

Upvotes: 1

Views: 4708

Answers (2)

dogbane
dogbane

Reputation: 274622

This is because createDialog blocks so bar.setValue will not be called until you hit OK on the dialog.

You should update the progress bar in a different thread.

For example:

    final JProgressBar bar = new JProgressBar(0,250000);
    bar.setValue(1000);
    bar.setIndeterminate(false);
    JOptionPane j = new JOptionPane(bar);

    Thread t = new Thread(){
        public void run(){
            for(int i = 1000 ; i < 250000 ; i+=10000){
                bar.setValue(i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }
    };
    t.start();

    final JDialog d = j.createDialog(j,"Expierment X");
    d.pack();
    d.setVisible(true);

Upvotes: 3

Faisal Feroz
Faisal Feroz

Reputation: 12785

You need to make sure that the setValue method gets called from the Event Dispatch Thread. You can use SwingUtilities.invokeLater for that.

Upvotes: 1

Related Questions