In this tutorial, we will show you how to use JProgressBar class to create progress bars in your Java swing application.
A progress bar is a widget that displays progress of a lengthy task, for instance file download or transfer. To create a progress bar in swing you use the JProgressbar class. With JProgressBar you can either create vertical or horizontal progress bar. In addition JProgressBar class allows you to create another kind of progress bar which is known as indeterminate progress bar. The indeterminate progress bar is used to display progress with unknown progress or the progress cannot express by percentage.
Here are the constructors of JProgressBar class:
Constructors | Meaning |
public JProgressBar() | Creates a horizontal progress bar. |
public JProgressBar(BoundedRangeModel model) | Creates a progress bar using BoundedRangeModel instance to hold data. |
public JProgressBar(int orient) | Creates a progress bar with a given orientation determined bySwingConstants.VERTICAL or SwingConstants.HORIZONTAL. |
public JProgressBar(int min, int max) | Creates a progress bar with mininum and maximum values. |
public JProgressBar(int orient, int min, int max) | Creates a progress bar with mininum and maximum values and progress bar’s orientation. |
Example of using JProgressbar
In this example, we will use JProgressBar class to create a simple progress bar.
package jprogressbardemo;
import java.awt.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
final int MAX = 100;
final JFrame frame = new JFrame("JProgress Demo");
// creates progress bar
final JProgressBar pb = new JProgressBar();
pb.setMinimum(0);
pb.setMaximum(MAX);
pb.setStringPainted(true);
// add progress bar
frame.setLayout(new FlowLayout());
frame.getContentPane().add(pb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
// update progressbar
for (int i = 0; i <= MAX; i++) {
final int currentValue = i;
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
pb.setValue(currentValue);
}
});
java.lang.Thread.sleep(100);
} catch (InterruptedException e) {
JOptionPane.showMessageDialog(frame, e.getMessage());
}
}
}
}
Code language: PHP (php)