import java.awt.Color; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.SwingUtilities; public class JProgressBarDemo { // Create a JFrame, JPanel, and JProgressBar private JFrame frame = new JFrame(); private JPanel panel = new JPanel(); JProgressBar progressBar = new JProgressBar(); // Set where the Progress Bar will start (visually) static final int MIN_BAR_VALUE = 0; static final int MAX_BAR_VALUE = 100; public static void main(String args[]) { new JProgressBarDemo(); } public JProgressBarDemo() { // Set the properties of the JProgressBar progressBar.setSize(250, 20); progressBar.setLocation(25, 45); progressBar.setForeground(Color.BLACK); progressBar.setBackground(Color.RED); // Set the point at which the Progress Bar begins moving progressBar.setMinimum(MIN_BAR_VALUE); progressBar.setMaximum(MAX_BAR_VALUE); // Set the properties of the JPanel panel = new JPanel(); panel.setLayout(null); panel.setBackground(Color.LIGHT_GRAY); // Set the properties of the JFrame frame.setLayout(null); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 150); frame.setTitle("Demo: JProgressBar"); frame.setLocationRelativeTo(null); // Add the JProgressBar to the JPanel; then add the JPanel to // the JFrame; then make the JFrame visible panel.add(progressBar); frame.setContentPane(panel); frame.setVisible(true); // Use a loop and a task delay to advance through the Progress Bar for (int i = MIN_BAR_VALUE; i <= MAX_BAR_VALUE; i++) { // For the scheduled task below, all variables must be declared // 'final' so that they cannot change while the task is being // processed final int value = i; try { // Update the GUI of the Progress Bar asynchronously (allow other // tasks to be run concurrently) on the AWT event dispatching // thread after all pending AWT events have been processed // http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingUtilities.html SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(value); } }); java.lang.Thread.sleep(80); // Sleep (pause) for 80 milliseconds } catch (InterruptedException e) { // Ignore any errors that occur } } } }