本帖最后由 吴亨 于 2011-12-21 17:22 编辑
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.SimpleDateFormat;
class MyCanvas extends Canvas
{
Long startTime = 0L;
Long endTime = 0L;
Graphics g =null;
public void paint(Graphics g)
{
g.fill3DRect(0,0,78,28,false);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date d0 = null;
try {d0 = sdf.parse("00:00:00");}
catch(Exception e) {e.printStackTrace();}
Date d = new Date(endTime - startTime + d0.getTime());
String strTime = sdf.format(d);
g.setColor(Color.WHITE);
g.drawString(strTime,10,20);
}
/////////* protected void processMouseEvent(MouseEvent e)
{
if(e.getID() == MouseEvent.MOUSE_PRESSED)
startTime = endTime = System.currentTimeMillis();
else if(e.getID() == MouseEvent.MOUSE_RELEASED)
{ endTime = System.currentTimeMillis();
repaint();
}
}
public MyCanvas()
{
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
*///////////// 这段代码可以换成下面的。
public MyCanvas()
{
this.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
startTime = System.currentTimeMillis();
}
public void mouseReleased(MouseEvent e)
{
endTime = System.currentTimeMillis();
repaint();
}
}
);
}
}
上面两段代码,用哪段好? |
|