日期:2014-05-20 浏览次数:20688 次
package tian.hong.zeng;
import java.awt.AWTEvent;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StopWatch extends Canvas implements Runnable{
/**
*
*/
private static final long serialVersionUID = 1L;
private long startTime = 0;
private long endTime = 0;
private boolean bStart = false;
public StopWatch(){
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
setSize(80, 30);
}
protected void processMouseEvent(MouseEvent e){
if(e.getID() == MouseEvent.MOUSE_PRESSED){
bStart = true;
startTime = endTime = System.currentTimeMillis();
//repaint();
new Thread(this).start();
}else if(e.getID() == MouseEvent.MOUSE_RELEASED){
//bStart = false;
//repaint();
}
super.processMouseEvent(e);
}
public void paint(Graphics g){
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SS");
Date elapseTime = null;
try{
elapseTime = sdf.parse("00:00:00:00");
}catch(Exception e){
e.printStackTrace();
}
elapseTime.setTime(endTime - startTime + elapseTime.getTime());
String display = sdf.format(elapseTime);
this.setBackground(Color.black);
g.setColor(Color.white);
Font font = new Font("Defaule", Font.PLAIN, 50);
g.setFont(font);
g.drawString(display, 20, 50);
}
public void run() {
// TODO Auto-generated method stub
while(bStart){
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
endTime = System.currentTimeMillis();
repaint();
}
}
}