JProgressBar
✅ Java Swing JProgressBar – Full Guide
JProgressBar is a Swing component that visually displays progress for tasks like downloading, uploading, or processing.
🔧 Common Properties & Methods
| Method / Property | Description |
|---|---|
setMinimum(int) |
Set minimum progress value (default 0) |
setMaximum(int) |
Set maximum progress value (default 100) |
setValue(int) |
Set current progress value |
getValue() |
Get current progress value |
setStringPainted(true) |
Show progress percentage as a string |
setIndeterminate(true) |
Show infinite progress (e.g., loading animation) |
setOrientation(...) |
Horizontal/Vertical (rarely used) |
✅ Basic Example: Progress Bar with Manual Update
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ProgressBarExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JProgressBar Example");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
JButton button = new JButton("Start");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Simulate loading in a separate thread
new Thread(() -> {
for (int i = 0; i <= 100; i++) {
try {
Thread.sleep(50); // Simulate work
} catch (InterruptedException ex) {
ex.printStackTrace();
}
progressBar.setValue(i);
}
}).start();
}
});
frame.add(progressBar);
frame.add(button);
frame.setVisible(true);
}
}
🌀 Optional: Indeterminate Mode (Loading...)
JProgressBar progressBar = new JProgressBar();
progressBar.setIndeterminate(true); // Shows an animated "in-progress" bar
🧠 Notes
-
Always update
JProgressBarfrom the Event Dispatch Thread (EDT) or useSwingWorkerfor background tasks. -
Use
setStringPainted(true)to display percentage.
Would you like an example with file upload simulation or one using SwingWorker for real background tasks?
Comments
Post a Comment