Java JProgressBar

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java JProgressBar

The JProgressBar class is used to display the progress of the task. It inherits JComponent class.

JProgressBar class declaration

Let's see the declaration for javax.swing.JProgressBar class.

public class JProgressBar extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:

Constructor

Description

JProgressBar()

It is used to create a horizontal progress bar but no string text.

JProgressBar(int min, int max)

It is used to create a horizontal progress bar with the specified minimum and maximum value.

JProgressBar(int orient)

It is used to create a progress bar with the specified orientation, it can be either Vertical or Horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants.

JProgressBar(int orient, int min, int max)

It is used to create a progress bar with the specified orientation, minimum and maximum value.

Commonly used Methods:

Method

Description

void setStringPainted(boolean b)

It is used to determine whether string should be displayed.

void setString(String s)

It is used to set value to the progress string.

void setOrientation(int orientation)

It is used to set the orientation, it may be either vertical or horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants.

void setValue(int value)

It is used to set the current value on the progress bar.

Java JProgressBar Example

  1. import javax.swing.*;    
  2. public class ProgressBarExample extends JFrame{    
  3. JProgressBar jb;    
  4. int i=0,num=0;     
  5. ProgressBarExample(){    
  6. jb=new JProgressBar(0,2000);    
  7. jb.setBounds(40,40,160,30);         
  8. jb.setValue(0);    
  9. jb.setStringPainted(true);    
  10. add(jb);    
  11. setSize(250,150);    
  12. setLayout(null);    
  13. }    
  14. public void iterate(){    
  15. while(i<=2000){    
  16.   jb.setValue(i);    
  17.   i=i+20;    
  18.   try{Thread.sleep(150);}catch(Exception e){}    
  19. }    
  20. }    
  21. public static void main(String[] args) {    
  22.     ProgressBarExample m=new ProgressBarExample();    
  23.     m.setVisible(true);    
  24.     m.iterate();    
  25. }    
  26. }    

Output:

JAVA Jprogressbar 1