Java Guides
In this post, I show you how to create a progress bar using the JProgressBar component in swing-based applications.
A progress bar is a component that is used when we process lengthy tasks. It is animated so that the user knows that our task is progressing. The JProgressBar component provides a horizontal or a vertical progress bar. The initial and minimum values are 0 and the maximum is 100.
Java Swing Progress Bar Example
package net.sourcecodeexamples.swingexample.components2; import javax.swing.AbstractAction; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.Timer; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import static javax.swing.GroupLayout.Alignment.CENTER; public class ProgressBarExample extends JFrame < private static final long serialVersionUID = 1L; private Timer timer; private JProgressBar progBar; private JButton startBtn; private final int MAX_VAL = 100; private void initializeUI() < progBar = new JProgressBar(); progBar.setStringPainted(true); startBtn = new JButton("Start"); startBtn.addActionListener(new ClickAction()); timer = new Timer(50, new UpdateBarListener()); createLayout(progBar, startBtn); setSize(350, 150); setTitle("JProgressBar"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); > private void createLayout(JComponent. arg) < JPanel pane = (JPanel) getContentPane(); GroupLayout gl = new GroupLayout(pane); pane.setLayout(gl); gl.setAutoCreateContainerGaps(true); gl.setAutoCreateGaps(true); gl.setHorizontalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addComponent(arg[1]) ); gl.setVerticalGroup(gl.createParallelGroup(CENTER) .addComponent(arg[0]) .addComponent(arg[1]) ); pack(); > private class UpdateBarListener implements ActionListener < @Override public void actionPerformed(ActionEvent e) < int val = progBar.getValue(); if (val >= MAX_VAL) < timer.stop(); startBtn.setText("End"); return; > progBar.setValue(++val); > > private class ClickAction extends AbstractAction < @Override public void actionPerformed(ActionEvent e) < if (timer.isRunning()) < timer.stop(); startBtn.setText("Start"); > else if (!"End".equals(startBtn.getText())) < timer.start(); startBtn.setText("Stop"); > > > public static void main(String[] args) < EventQueue.invokeLater(() -> < ProgressBarExample progressBarExample = new ProgressBarExample(); progressBarExample.initializeUI(); progressBarExample.setVisible(true); >); > >
Here we created the JProgressBar component. The minimum value is 0, the maximum 100, and the initial value is 0. These are the default values. The setStringPainted() method determines whether the progress bar displays the percentage of the task completed:
progBar = new JProgressBar(); progBar.setStringPainted(true);
The timer object launches UpdateBarListener every 50ms. Inside the listener, we check if the progress bar reached its maximum value:
timer = new Timer(50, new UpdateBarListener());
The actionPerformed() method of the listener increases the current value of the progress bar. If it reaches the maximum value, the timer is stopped and the button’s label is set to «End»:
private class UpdateBarListener implements ActionListener < @Override public void actionPerformed(ActionEvent e) < int val = progBar.getValue(); if (val >= MAX_VAL) < timer.stop(); startBtn.setText("End"); return; > progBar.setValue(++val); > >
The button starts or stops the timer. The text of the button is updated dynamically; it can have «Start», «Stop», or «End» string values:
private class ClickAction extends AbstractAction < @Override public void actionPerformed(ActionEvent e) < if (timer.isRunning()) < timer.stop(); startBtn.setText("Start"); > else if (!"End".equals(startBtn.getText())) < timer.start(); startBtn.setText("Stop"); > > >
Output
Related Swing Examples
- Java Swing Exit Button— In this post, I show you how to exit a Swing application when clicking on the exit button.
- Swing ToolTip Tutorial with Example— In this tutorial, we will learn how to add tooltip text to a Swing component.
- Java Swing BorderLayout Example — In this example, we will learn how to use BorderLayout in GUI/swing based applications.
- Java Swing GridLayout Tutorial with Examples — In this tutorial, we will learn how to use GridLayout in GUI/swing based applications.
- Swing Mouse Move Events using MouseMotionAdapter — In this tutorial, we will learn how to receive mouse motion events using MouseMotionAdapter.
- Java Swing CheckBox Example — In this post, I show you how to use JCheckBox class to create a Radio button in a Swing-based application .
- Java Swing Radio Button Example— In this post, I show you how to use JRadioButton class to create a Radio button in a Swing-based application.
- Java Swing Progress Bar Example — In this post, I show you how to create a progress bar using the JProgressBar component in swing-based applications.
- Java Swing Combo Box Example — In this post, I show you how to create a combo box using a JComboBox component in swing-based applications.
- Java Swing Slider Example— In this post, I show you how to create a slider using the JSlider component in swing-based applications.
- Java Swing Toggle Button Example — In this post, we will learn how to create a toggle button using the JToggleButton component in swing-based applications.
Class JProgressBar
A component that visually displays the progress of some task. As the task progresses towards completion, the progress bar displays the task’s percentage of completion. This percentage is typically represented visually by a rectangle which starts out empty and gradually becomes filled in as the task progresses. In addition, the progress bar can display a textual representation of this percentage.
JProgressBar uses a BoundedRangeModel as its data model, with the value property representing the «current» state of the task, and the minimum and maximum properties representing the beginning and end points, respectively.
To indicate that a task of unknown length is executing, you can put a progress bar into indeterminate mode. While the bar is in indeterminate mode, it animates constantly to show that work is occurring. As soon as you can determine the task’s length and amount of progress, you should update the progress bar’s value and switch it back to determinate mode.
Here is an example of creating a progress bar, where task is an object (representing some piece of work) which returns information about the progress of the task:
progressBar = new JProgressBar(0, task.getLengthOfTask()); progressBar.setValue(0); progressBar.setStringPainted(true);
Here is an example of querying the current state of the task, and using the returned value to update the progress bar:
progressBar.setValue(task.getCurrent());
Here is an example of putting a progress bar into indeterminate mode, and then switching back to determinate mode once the length of the task is known:
progressBar = new JProgressBar(); . //when the task of (initially) unknown length begins: progressBar.setIndeterminate(true); . //do some work; get length of task. progressBar.setMaximum(newLength); progressBar.setValue(newValue); progressBar.setIndeterminate(false);
For complete examples and further documentation see How to Monitor Progress, a section in The Java Tutorial.
Warning: Swing is not thread safe. For more information see Swing’s Threading Policy.
Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans has been added to the java.beans package. Please see XMLEncoder .