How to use JProgressBar

╄→尐↘猪︶ㄣ 提交于 2019-12-05 20:35:57

You can't call Thread.sleep(...) on the main Swing thread, the EDT or "event dispatch thread", as this will do nothing but put your entire application, progress bar and all, to sleep. Likely you're seeing nothing happening for 1 second, then bingo, the entire progress bar is filled.

I suggest that instead of Thread.sleep, you use a Swing Timer for this part, or else if you want to eventually monitor a long-running process, use a background thread such as a SwingWorker. SwingWorkers are discussed in the JProgressBar tutorial.

e.g., with a Timer:

public void viewBar() {

  progressbar.setStringPainted(true);
  progressbar.setValue(0);

  int timerDelay = 10;
  new javax.swing.Timer(timerDelay , new ActionListener() {
     private int index = 0;
     private int maxIndex = 100;
     public void actionPerformed(ActionEvent e) {
        if (index < maxIndex) {
           progressbar.setValue(index);
           index++;
        } else {
           progressbar.setValue(maxIndex);
           ((javax.swing.Timer)e.getSource()).stop(); // stop the timer
        }
     }
  }).start();

  progressbar.setValue(progressbar.getMinimum());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!