package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test implements ActionListener{
JFrame jf;
JPanel jp;
JLabel jl;
JButton button;
//声明线程标记,为true则线程为开启状态,或者可以开启线程,为false则线程为暂停状态或者可以暂停
boolean flag = true;
//声明标志位,记录当前线程的位置
int n = 100;
public Test() {
jf = new JFrame("倒计时");
jp = new JPanel();
jl = new JLabel();
button = new JButton("开始");
button.addActionListener(this);
jp.add(jl);
jp.add(button);
jf.add(jp);
jf.setSize(300, 200);
jf.setLocation(200, 200);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String comm = e.getActionCommand();
MyThread t = new MyThread();
if("开始".equals(comm)) {
t.start();
button.setText("暂停");
}else if("暂停".equals(comm)) {
flag = false;
button.setText("开始");
}
}
class MyThread extends Thread {
public void run() {
for(int i = n; i > 0; i--) {
//如果点击了暂停,则记住当前的位置,并设置标记为true
if(!flag) {
flag = true;
n = i + 1;
break;
}
jl.setText(i + "");
try {
this.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new Test();
}
}