如何将进度条进行开始和暂停的操作?

创建2个按钮对象,定义一个静态整型成员变量。定义的这个变量是用来表示点击的哪个按钮,点击“开始”,变量值为1,“暂停”值为0.该变量不能在方法内部定义。

 

 

JButton a,b;
static int m=0;

 显示窗口:

 

 

public void showi(){
		this.setTitle("游戏");                
        this.setLayout(new FlowLayout());
		this.setSize(600,500);
		JProgressBar p=new JProgressBar();//创建一个进度条对象
		p.setMaximum(300);//设置进度条的最大值是300
		this.add(p);//将进度条加到窗体上
		a=new JButton("开始");
		b=new JButton("暂停");
		this.add(a);
		this.add(b);
		this.setResizable(true);//是否能最大化
		this.setDefaultCloseOperation(3);//关闭窗体是退出程序
		this.setLocationRelativeTo(null);//窗体居中显示
		this.setVisible(true);//窗体可见
		this.validate();
		Test6 t=new Test6(p);//创建一个线程
		t.start();//启动线程
		ActionListener a1=new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(e.getSource()==a){m=1;} //如果点击开始按钮,m的值为1
				else if(e.getSource()==b){ m=0;}//如果点击暂停按钮,m的值为0
			}
		};
              //给按钮添加监视器
             a.addActionListener(a1);
	    b.addActionListener(a1);
}
 

 下面就是线程的类

 

public class Test6 extends Thread{
	JProgressBar p;
	static int x=0;
	public Test6(JProgressBar p){
		this.p=p;
	}
	public void run(){
		jin();
	}
	public void jin(){
		while(true){
			p.setValue(x);//设置进度条的当前值
		   if(Test5.m==1)	x+=5;
			try{
				Thread.sleep(200);
				}catch(Exception e){
				}
		}
	}
}

 程序结果:进度条的初始值是0,点击“开始”,进度条开始移动,点击“暂停”,进度条暂停,在点击”开始“,进度条又开始移动。
 
如何将进度条进行开始和暂停的操作?