How to use JProgressBar

Jayanga Kaushalya picture Jayanga Kaushalya · Sep 13, 2011 · Viewed 9k times · Source

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

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Sep 13, 2011

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