java多线程制作计时器

基本思路:

在类中创建thread 供按钮监听器调用。

 

 

界面设计:

 

代码:

 1 package thread;
 2 
 3 import java.awt.*;
 4 import java.awt.event.*;
 5 
 6 import javax.swing.*;
 7 
 8 public class Threadtest extends JFrame implements Runnable{
 9     JFrame frm=new JFrame("watch");
10     JPanel bottom=new JPanel();
11     JPanel mid=new JPanel();
12     JLabel h=new JLabel("0");
13     JLabel biao=new JLabel(":");
14     JLabel s=new JLabel("00");
15     JButton hajime=new JButton("开始计时");
16     JButton pause=new JButton("暂停");
17     JButton tozero=new JButton("清零");
18     Thread t=new Thread(this);    
19     private int i=0,j=0;
20     public void run(){
21         try
22         {
23             while(true){
24             Thread.sleep(100);
25             i++;
26             if(i>=1&&i<10)
27             {
28                 s.setText("0"+i);
29             }
30             else if(i>=10&&i<60)
31                 s.setText(""+i);
32             if(i==60)
33             {
34                 i=0;
35                 j++;
36                 s.setText("00");
37                 h.setText(""+j);
38             }
39             }
40         }catch(Exception e){
41             System.out.println("");
42         }
43     }
44     public Threadtest()
45     {
46         frm.setLayout(new BorderLayout());
47         frm.setBounds(200, 200, 300, 150);
48         frm.setVisible(true);
49         frm.add("South",bottom);
50         frm.add("Center",mid);
51         
52         mid.add(h);
53         mid.add(biao);
54         mid.add(s);
55         h.setFont(new Font("Consulas",Font.PLAIN,36));
56         biao.setFont(new Font("Consulas",Font.PLAIN,36));
57         s.setFont(new Font("Consulas",Font.PLAIN,36));
58         bottom.add(hajime);
59         bottom.add(pause);
60         bottom.add(tozero);
61         
62         
63         hajime.addActionListener(new ActionListener(){
64             public void actionPerformed(ActionEvent e){
65                 if(t.isAlive())
66                     t.resume();
67                 else t.start();
68             }});
69         pause.addActionListener(new ActionListener(){
70             public void actionPerformed(ActionEvent e){
71                     t.suspend();
72             }});
73         tozero.addActionListener(new ActionListener(){
74             public void actionPerformed(ActionEvent e){
75                 h.setText("0");
76                 s.setText("00");
77                 i=0;
78                 j=0;
79             }
80         });
81     }
82     
83     public static void main(String[] args){
84         new Threadtest();
85     }
86 }
View Code

 

posted @ 2014-12-30 19:10  verlen  阅读(2032)  评论(0编辑  收藏  举报