开发者

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

开发者 https://www.devze.com 2023-01-19 13:41 出处:网络
Hey all, I have a pretty simple problem someone should be abl开发者_运维知识库e to help me with. All I want is a small frame with a progress bar that updates, right now it\'s not updating:

Hey all, I have a pretty simple problem someone should be abl开发者_运维知识库e 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!


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号