自定义组件(计时器):
package gui.test06;
import java.awt.AWTEvent;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StopWatch extends Canvas implements Runnable {
long startTime = 0;
long endTime = 0;
//线程标志状态
private boolean bStart;
public StopWatch() {
//
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
public void paint(Graphics g) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date elapsedTime = null;
try {
elapsedTime = sdf.parse("00:00:00");
} catch (ParseException e) {
e.printStackTrace();
}
elapsedTime.setTime(elapsedTime.getTime() + endTime - startTime);
String strTime = sdf.format(elapsedTime);
g.fill3DRect(0, 0, 78, 28, false);
g.setColor(Color.WHITE);
g.drawString(strTime, 10, 20);
}
@Override
protected void processMouseEvent(MouseEvent e) {
if (e.getID() == MouseEvent.MOUSE_PRESSED) {
startTime = endTime = System.currentTimeMillis();
bStart = true;
//新启动一个线程去跑
new Thread(this).start();
} else if (e.getID() == MouseEvent.MOUSE_RELEASED) {
endTime = System.currentTimeMillis();
bStart = false;
}
repaint();
}
@Override
public void run() {
while (bStart) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
endTime = System.currentTimeMillis();
repaint();
}
}
}