Java Swing复习(11)进度条(涉及多线程)

时间:2023-01-28 12:06:11
package www10m10;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;

public class TestJProgressBar {
	private JFrame jf;
	private JProgressBar jpb;
	private JButton jb;
	
	public TestJProgressBar() {
		jf=new JFrame();
		jpb=new JProgressBar();
		jb=new JButton("start");
	}
	
	private void init(){
		jf.setLayout(new FlowLayout());
		jf.add(jpb);
		jf.add(jb);
	}
	
	private void setStyle(){
		jpb.setStringPainted(true);
	}
	
	private void addEventHandler(){
		jb.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				new Thread(){
					public void run() {
						for (int i = 0; i <= 100; i++) {
							try {
								Thread.sleep(100);
							} catch (InterruptedException e1) {
								e1.printStackTrace();
							}
							jpb.setValue(i);
						}
					}
				}.start();
				
				
			
				
			}
		});
	}
	
	public void show(){
		init();
		setStyle();
		addEventHandler();
		jf.pack();
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void main(String[] args) {
		new TestJProgressBar().show();
	}
}