views:

62

answers:

2

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!

+1  A: 

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

Faisal Feroz
This is a good point, but this isn't the repainting problem.
Erick Robertson
+2  A: 

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);
dogbane