Progress Bar in Java

The other day, I was searching for Progress Bars to be used in Swing applications. Search for a suitable Java code was not fruitful. One code displayed the progress bar, but not the percentage of the process completed. Here’s a code, that incorporates all of these into a single program.

Please post a comment if you have any questions. 🙂


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

public class Main extends JPanel {

JProgressBar pbar;
static int min = 0;
static int max = 100;

public Main() {
pbar = new JProgressBar();

pbar.setMinimum(min);
pbar.setMaximum(max);
pbar.setStringPainted(true);

add(pbar);

JFrame frame = new JFrame("Progress Bar Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(this);
frame.pack();
frame.setVisible(true);
frame.setSize(200,100);

for (int i = min; i <= max; i++) {
final int percent = i;
try {

SwingUtilities.invokeLater(new Runnable() {

public void run() {
updateBar(percent);
}
});

Thread.sleep(20);
} catch (InterruptedException e) {
}
}
}

public void updateBar(int newValue) {
pbar.setValue(newValue);
pbar.setString(newValue+" % Completed");
}

public static void main(String args[]) {
new Main();
}
}

Progress Bar Example

Progress Bar Example

Advertisements

About Manikandan Surendren

A PeopleSoft Techno-functional Consultant. An engineering graduate in Computer Science. Technology Enthusiast. Movie freak. Gadget geek.
This entry was posted in Code. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s