ProgressBar doesn't change its value in Java

后端 未结 2 517
故里飘歌
故里飘歌 2021-01-18 08:48

I have strange problem. I set a JProgressBar:

private JProgressBar progressBar;

public void foo()
{
    ...
    progressBar = new JProgressBar(0, 100);
             


        
相关标签:
2条回答
  • 2021-01-18 09:27

    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:

    1. (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();
      }
      
    2. 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)
  • 2021-01-18 09:27

    Even though this question was answered already I've found another way that actually worked for me. I was using the swing worker and using propertyChange(null) to update the progress bar was the easiest solution.

    Just wanted to offer this alternative.

    0 讨论(0)
提交回复
热议问题