package Day0822; import java.awt.event.*; import javax.swing.*; import java.awt.*; public class HomeWork implements ActionListener,Runnable{ private int x = 0; private int y = 0; private int z = 0; private int num = 0; private JFrame jf; private JPanel jp; private JButton jb; private JButton jb1; private JButton jb2; private JTextField jtf; private boolean flag = true; private Thread thread = new Thread(this); public void init(){ jf = new JFrame("*********秒表*********"); jp = new JPanel(); jb = new JButton("开始"); jb1 = new JButton("暂停"); jb2 = new JButton("重置"); jtf = new JTextField(9); jf.setSize(300,150); jf.setLocationRelativeTo(null); jf.setLayout(new FlowLayout()); jf.setResizable(false); jtf.setFont(new Font("楷体",1,50)); jtf.setHorizontalAlignment(JTextField.CENTER); jtf.setText(setTime()); jb.addActionListener(this); jb1.addActionListener(this); jb2.addActionListener(this); jf.add(jtf); jf.add(jb); jf.add(jb1); jf.add(jb2); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } public void actionPerformed(ActionEvent e){ if(e.getSource().equals(jb)){ flag = true; new Thread(this).start(); } if(e.getSource().equals(jb1)){ flag = false; } if(e.getSource().equals(jb2)){ flag = false; //线程终止 num = 0; x = 0; y = 0; z = 0; jtf.setText("0:0:0"); } } public void run(){ while(flag){ try { Thread.sleep(1000); num = num+1; z=(num)%60; y = (num/60)%60; x = (num/3600)%24; } catch (InterruptedException e) { e.printStackTrace(); }finally{ jtf.setText(setTime()); } } } public String setTime(){ return x+":"+y+":"+z; } public String setTime1(){ return "0"+x+":0"+y+":0"+z; } public static void main(String[] arge){ HomeWork hw = new HomeWork(); hw.init(); } }