JProgressBar Class of Swing in Java

Introduction

 
In this article, we discuss the JProgressBar class of Swing in Java.
 

What is JProgressBar class?

 
JProgressBar class displays the progress of the class.
 
Some commonly used public constructors are:
  • JProgressBar()
          Creates a default progress bar without a string.
  • JProgressBar(int minimum, int maximum)
          Created with the specified minimum and maximum values of the horizontal progress bar.
  • JProgressBar(int orient)
          Creates a progress bar usng the specified orientation.
  • JProgressBar(int orient, int minimum, int maximum)
          Creates a progress bar with the specified orientation, min and max values.
 
Some commonly used public methods are:
  • void setStringPainted(boolean bln)
          Specifies whether the progress should display a string.
  • void setString(String str)
          It sets the value of the progress bar.
  • void setOrientation(int orient)
          It sets the orientation of the progrss bar.
  • void setValue(int val)
         It sets the current value of the current string.
 
Let's take an example
 
JProgressBarEx.java
 
In this example; we create a simple progress bar class using Swing that shows the progress of the class.
  1. import javax.swing.*;  
  2. public class JProgressBarEx extends JFrame  
  3. {  
  4.  JProgressBar jprgrssbr;  
  5.  int x = 0, n = 0;  
  6.  JProgressBarEx()  
  7.  {  
  8.   jprgrssbr = new JProgressBar(12110);  
  9.   jprgrssbr.setBounds(454520435);  
  10.   jprgrssbr.setValue(0);  
  11.   jprgrssbr.setStringPainted(true);  
  12.   add(jprgrssbr);  
  13.   setSize(500500);  
  14.   setLayout(null);  
  15.  }  
  16.  public void iterate()  
  17.  {  
  18.   while (x <= 2110)  
  19.   {  
  20.    jprgrssbr.setValue(x);  
  21.    x = x + 22;  
  22.    try  
  23.    {  
  24.     Thread.sleep(200);  
  25.    }   
  26.    catch (Exception ey)  
  27.    {}  
  28.   }  
  29.  }  
  30.  public static void main(String args[])  
  31.  {  
  32.   JProgressBarEx mthd = new JProgressBarEx();  
  33.   mthd.setVisible(true);  
  34.   mthd.iterate();  
  35.  }  
  36. }   
Output
 
Fig-1.jpg
  
After running the program a window is generated that shows the progress of the program.
 
Fig-2.jpg
 
After a few seconds the progress bar shows the following:
 
Fig-3.jpg