Jul 14

People often have problems using a JProgressBar. Hopefully the following example will help got you started.

import java.awt.EventQueue;

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

public class Progress extends JPanel {

	private JProgressBar bar = new JProgressBar(0, 10000);

	public Progress() {
		add(bar);
	}

	public void start() {
		new Thread(new ProgressThread()).start();
	}

	public static void main(String[] args) {

		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
		Progress progress = new Progress();
		frame.add(progress);
		frame.pack();
		frame.setVisible(true);

		progress.start();
	}

	class ProgressThread implements Runnable {
		public void run() {
			for (int i=0; i<10000; i++) {
				final int value = i;
				
				pause();   // just to slow the progress down a little
				
				// Need to call setValue() on the EDT so we use invokeLater()
				
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						bar.setValue(value);
					}
				});
			}
		}

		private void pause() {
			try {
				Thread.sleep(5);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

written by objects \\ tags: ,


Leave a Reply

You must be logged in to post a comment.