Canvas类:
1: import java.awt.Frame;
2: import java.awt.event.WindowAdapter;
3: import java.awt.event.WindowEvent;
4:
5: import java.awt.AWTEvent;
6: import java.awt.Canvas;
7: import java.awt.Color;
8: import java.awt.Graphics;
9: import java.awt.event.MouseEvent;
10: import java.text.ParseException;
11: import java.text.SimpleDateFormat;
12: import java.util.Date;
13:
14: class StopWatch extends Canvas implements Runnable {
15: private long startTime = 0;
16: private long endTime = 0;
17: private boolean bStart = false ;
18:
19: public StopWatch() {
20: enableEvents(AWTEvent. MOUSE_EVENT_MASK );
21:
setSize(80, 30);
22:
}
23:
24: protected void processMouseEvent(MouseEvent e) {
25: if (e.getID() == MouseEvent. MOUSE_PRESSED ) {
26: bStart = true ;
27: startTime = endTime = System.currentTimeMillis();
28:
repaint();
29: new Thread( this ).start();
30: } else if (e.getID() == MouseEvent. MOUSE_RELEASED ) {
31: bStart = false ;
32:
repaint();
33:
}
34:
}
35:
36: @Override
37: public void paint(Graphics g) {
38: super .paint(g);
39: // 时间值的小时,分,秒用两位数字显示,不足两位的部分前面加0,即 "HH:mm:ss"
40: SimpleDateFormat sdf = new SimpleDateFormat( "HH:mm:ss" );
41: Date elapsedTime = null ;
42: try {
43: elapsedTime = sdf.parse( "00:00:00" );
44: } catch (ParseException e) {
45:
e.printStackTrace();
46:
}
47: // elapsedTime.setTime(endTime - startTime)不是"00:00:00" 而是"08:00:00"
48: elapsedTime.setTime( endTime - startTime + elapsedTime.getTime());
49:
String display = sdf.format(elapsedTime);
50:
g.drawRect(0, 0, 78, 28);
51: g.fill3DRect(2, 2, 75, 25, true );
52: g.setColor(Color. red );
53:
g.drawString(display, 10, 20);
54:
}
55:
56: @Override
57: public void run() {
58: while ( bStart ) {
59: try {
60:
Thread.sleep(500);
61: } catch (InterruptedException e) {
62:
e.printStackTrace();
63:
}
64: endTime = System.currentTimeMillis();
65:
repaint();
66:
}
67:
}
68:
69:
}
Main类(程序入口):
1: public class TestStopWatch {
2: public static void main(String[] args) {
3: Frame f = new Frame( "StopWatch" );
4: f.add( new StopWatch());
5:
f.setSize(200, 200);
6: f.setVisible( true );
7: f.addWindowListener( new WindowAdapter() {
8:
9: @Override
10: public void windowClosing(WindowEvent e) {
11: super .windowClosing(e);
12:
System.exit(0);
13:
}
14:
});
15:
}
16:
}