java progressbar,ProgressBar不会在Java中更改其值

I have strange problem. I set a JProgressBar:

private JProgressBar progressBar;

public void foo()

{

...

progressBar = new JProgressBar(0, 100);

progressBar.setValue(0);

progressBar.setStringPainted(true);

...

contentPane.add(progressBar);

...

}

But it changes only when I put setValue function it in some places in code, not everywhere:

public void foo2()

{

progressBar.setValue(100); //working

if(...)

{

System.out.println("These instructions are executing"); //working

progressBar.setValue(0); //not working

}

}

So, what am I doing wrong? Why the second instruction doesn't work?

解决方案

The value of the progress bar is really updated. But it isn't simply on the screen yet. Often, we use progress bars in loops. But, while you are in the loop, which you probably invoked by clicking a button it isn't painted. Why? Because you invoked it by clicking a button. When you click a button, all the code you've made for that button is being executed by the AWTEventThread. This is the same thread that keep track of all the Swing components, and checks wether they have to be repainted. That is the thread that makes your JFrame come alive. When you hover a button and the color changes a bit, it's done by the AWTEventThread.

So, while you are working in the loop, the AWTEventThread can't update the screen anymore.

This means there are two solutions:

(Recommend) You should create a separate thread which executes the loop. This means the AWTEventThread can update the screen if necessary (when you call bar.setValue(...);)

public void yourButtonClickMethod()

{

Runnable runner = new Runnable()

{

public void run() {

//Your original code with the loop here.

}

};

Thread t = new Thread(runner, "Code Executer");

t.start();

}

Manually repaint the progress bar. I did it always with bar.repaint(); but I'm wondering if it will work. I though it was that method. If that doesn't work, try: bar.update(bar.getGraphics());.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值