A Progress Bar Example Program

Java Code:

Progress Bar The Java code listing indicates an example of the way to use the JProgressBar and SwingWorker instructions. When run the Java software will display a GUI which includes a JButton, a JProgressBar and JCheckBoxes. The JButton begins a simulated undertaking whose development is tracked by means of the JProgressBar. The JCheckBoxes control whether the development is determined or indeterminate.

The article that is going with this case software is How to Make a Progress Bar.

Progress Bar coding

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JProgressBar;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingWorker;
import java.awt.BorderLayout;
import java.util.List;
public class ProgressBarExamples {
JProgressBar progressBar;
JCheckBox progressType;
JCheckBox switchType;
final JButton goButton;
//Note: Typically the main method will be in a
//separate class. As this is a simple one class
//example it's all in the one class.
public static void main(String[] args) {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
public void run()
new ProgressBarExamples();
public ProgressBarExamples()
JFrame guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setTitle("Creating a Table Example");
//This will center the JFrame in the middle of the screen
goButton = new JButton("Go");
goButton.addActionListener(new ActionListener()
//When the button is clicked the SwingWorker class is executed and
//the button is disabled
public void actionPerformed(ActionEvent event)
Sleeper task = new Sleeper();
//create a panel to hold the checkboxes
JPanel chkPanel = new JPanel();
//Create a checkbox to pick between a determined or indeterminate
progressType = new JCheckBox("Determined Progress Bar", true);
progressType.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent event)
//Create a checkbox to switch progress bar modes
switchType = new JCheckBox("Switch to Determined");
//create progress bar
progressBar = new JProgressBar(0, 100);
guiFrame.add(goButton, BorderLayout.WEST);
guiFrame.add(progressBar, BorderLayout.CENTER);
guiFrame.add(chkPanel, BorderLayout.SOUTH);
//SwingWorker class is used to simulate a task being performed
class Sleeper extends SwingWorker {
public Void doInBackground() throws InterruptedException {
int progress = 0;
while (progress chunks) {
for (Integer chunk : chunks) {
//if the switchtype checkbox is selected then
//change the progressbar to a determined type
//once the progress has reached 50
if (chunk > 49)
if (switchType.isEnabled() && switchType.isSelected())
//when the 'task' has finished re-enable the go button
public void done() {