JProgressBar – Java Swing – Example
In this tutorial, we are going to see an example of JProgressBar in Java Swing. JProgressBar is part of the Java Swing package. JProgressBar visually displays the progress of a specified task. JProgressBar displays the percentage of completion of the specified task. The progress bar fills up when the task is completed. In addition to displaying the percentage of task completion, it can also display text.
JProgressBar constructors class:
JProgressBar() | Create a progress bar without text on it. |
JProgressBar(int orientation) | Creates a progress bar with a specified orientation. If SwingConstants.VERTICAL is transmitted as argument, a vertical progress bar is created, if SwingConstants.HORIZONTAL is transmitted as argument, a horizontal progress bar is created. |
JProgressBar(int min, int max) | Creates a progress bar with a specified minimum and maximum value. |
JProgressBar(int orientation, int min, int max) | Creates a progress bar with a specified minimum and maximum value and a specified orientation. If SwingConstants.VERTICAL is transmitted as argument, a vertical progress bar is created, if SwingConstants.HORIZONTAL is transmitted as argument a horizontal progress bar is created. |
[st_adsense]
Commonly used methods:
- int getMaximum(): returns the maximum value of the progress bar.
- int getMinimum(): returns the minimum value of the progress bar.
- String getString(): get a string representation of the current value of the progress bar.
- void setMaximum(int n): sets the maximum value of the progress bar to n value.
- void setMinimum(int n): sets the minimum value of the progress bar to n value.
- void setValue(int n): sets the current value of the progress bar to n value.
- void setString(String str): set the value of the progress bar to str.
Example of JProgressBar in Java Swing:
import javax.swing.*; public class ProgressBarTest extends JFrame { JProgressBar progress; ProgressBarTest() { // Create the progressBar progress = new JProgressBar(0,1000); // Set the position of the progressBar progress.setBounds(35,40,165,30); // Initialize the progressBar to 0 progress.setValue(0); // Show the progress string progress.setStringPainted(true); // Add the progressBar to the frame add(progress); setSize(250,150); setLayout(null); } // function to increase the progressBar public void loop() { int i=0; while(i <= 1000) { // fills the bar progress.setValue(i); i = i + 10; try { // delay the thread Thread.sleep(120); } catch(Exception e){} } } public static void main(String[] args) { ProgressBarTest frame = new ProgressBarTest(); frame.setVisible(true); frame.loop(); } }
Output:
[st_adsense]