// Uses a JProgressBar import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JProgressBarApp extends JPanel implements Runnable { // 1. Create a JProgressBar and a JButton JProgressBar bar = new JProgressBar(); JButton btn = new JButton("Start"); public JProgressBarApp() { setLayout(new BorderLayout()); // 2. Initialize the JProgressBar, add to App bar.setBorderPainted(true); bar.setStringPainted(true); bar.setValue(0); add(bar, BorderLayout.NORTH); // 3. Add JButton to south in FlowLayout panel JPanel p = new JPanel( new FlowLayout(FlowLayout.CENTER)); p.add(btn); add(p, BorderLayout.SOUTH); // 4. Start a new task when Start button pressed btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { new Thread(JProgressBarApp.this).start(); } }); } // Task when Start button is pressed public void run() { // 1. Disable the Start button btn.setEnabled(false); // 2. Choose a random job length int jobLength = (int)(Math.random() * 1000) + 100; // 3. Initialize the JProgressBar bar.setMaximum(jobLength); // How long is the job? bar.setString(null); // Display % while painting bar.setValue(0); // Start at 0 for (int i = 0; i < jobLength; i++) { // 4. After each "chunk", update the progress bar bar.setValue(i); try { Thread.sleep(10); } catch (InterruptedException ie) { } } // 5. Change the string displayed in the progress bar bar.setValue(jobLength); bar.setString("Job Finished"); // 6. Reset the Start button btn.setEnabled(true); } public static void main(String[] args) { new GApp("The JProgressBar Application", new JProgressBarApp()).show(); } }