Progress Bar in Java Swing library
Submitted by pavel7_7_7 on Monday, September 8, 2014 - 16:37.
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:
To place all the GUI elements we will use a JPanel with BoxLayout:
Now we can add
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:
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
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.
- extends JComponent
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;
A vertical glue is added to the top of the frame for better look of the application.
The first type of JProgressBar is an
infiniteprogress bar. To create an infinite progress bar you can use the following code:
- infinite.setIndeterminate(true);
infiniteprogress bar to the panel:
- ProgressPanel.add(infinite);
- percentage.setStringPainted(true);
- percentage.setMinimum(0);
- percentage.setMaximum(100);
- ProgressPanel.add(percentage);
Now we can add the buttons to this panel:
The last step with GUI is to add buttons panel to the ProgressPanel:
- ProgressPanel.add(buttons);
- this.getContentPane().add(ProgressPanel);
Add progresswill increment the progress with 5 percents:
- @Override
- int percents = percentage.getValue();
- percents += 5;
- if(percents < percentage.getMaximum())
- percentage.setValue(percents);
- else
- percentage.setValue(percentage.getMaximum());
- }
- });
- @Override
- infinite.setIndeterminate(false);
- infinite.setString(null);
- }
- });
Add new comment
- 246 views