Progress Bar in Java Swing library
Some of the applications perform actions that can take a big amount of time. In this case you need to keep a connection with the user to show that your application doesn't stop to work or a failure happens. For this task a good way is to use a progress bar in your application.
Java Swing library provides a class that implements progress bar:
To test JProgressBar class create new project with class ProgressBarDemo:
All the GUI elements will be defined in the constructor of the class. We will create a frame with 2 buttons and 2 types of progress bars.
To use JProgressBar class you need to add import of this class:
- import javax.swing.JProgressBar;
To place all the GUI elements we will use a JPanel with BoxLayout:
A vertical glue is added to the top of the frame for better look of the application.
The first type of JProgressBar is an
progress bar. To create an infinite progress bar you can use the following code:
Now we can add
progress bar to the panel:
Another type of progress bar is a progress bar with percentage:
To show the progress of the action you need set PaintedString:
For this progress bar we can set the range of values. We will use percentage, so the interval is set from 0 to 100:
Now we can add it to the panel:
To test progress bars work we will have a panel with buttons for different actions with progress bars:
Now we can add the buttons to this panel:
The last step with GUI is to add buttons panel to the ProgressPanel:
And the ProgressPanel is added to the frame:
We need to manipulate progress bars. For this purpose we need to add actions listeners for both buttons. The first button
will increment the progress with 5 percents:
This Listener increment the value of the progress bar if it's possible.
Now we can write the listener for infinite progress bar that will stop the progress:
Now you know the basic operation with progress bars and you can keep the dialog with the user even if your application is performing a long term actions.