How to use JProgressBar

泪湿孤枕 提交于 2019-12-12 09:54:31

问题


I want to use JProgressBar and it must be loaded in one second. I don't want wait for any task to complete. Just want to fill the progress bar in one second. So I write following code. But it doesn't working. progress bar wasn't filling. I am new to Java. Please can anyone help me.

    public void viewBar() {
progressbar.setStringPainted(true); progressbar.setValue(0); for(int i = 0; i <= 100; i++) { progressbar.setValue(i); try { Thread.sleep(10); } catch (InterruptedException ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); } } progressbar.setValue(progressbar.getMinimum()); }


回答1:


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


来源:https://stackoverflow.com/questions/7403729/how-to-use-jprogressbar

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