- Java code
import java.awt.event.*;import java.awt.*;class TestStopWatch extends Frame{ public TestStopWatch() { this.add(new StopWatch()); addWindowListener(new WindowAdapter() { public void WindowClosing(WindowEvent e) { dispose(); System.exit(0); } }); } public static void main(String []args) { TestStopWatch sw=new TestStopWatch(); }}
- Java code
import java.awt.*;import java.awt.Canvas;import java.text.SimpleDateFormat;import java.util.Date;import java.awt.event.*;public class StopWatch extends Canvas implements Runnable{ long startTime=0; long endTime=0; boolean start=false; public StopWatch() { enableEvents(AWTEvent.MOUSE_EVENT_MASK); } protected void processMouseEvent(MouseEvent e) { if(e.getID()==MouseEvent.MOUSE_CLICKED) { startTime=endTime=System.currentTimeMillis(); repaint(); start=true; new Thread(this).start(); }else if(e.getID()==MouseEvent.MOUSE_RELEASED) { endTime=System.currentTimeMillis(); repaint(); start=false; } } public void paint(Graphics g) { SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss"); Date date=null; try { date=sdf.parse("00:00:00"); }catch(Exception e) { e.printStackTrace(); } date.setTime(date.getTime()+endTime-startTime); //new Date(endTime-startTime); String strName=sdf.format(date); g.fill3DRect(0,0,78,28,true); g.setColor(Color.WHITE); g.drawString(strName,10,20); } public void run() { while(start) { try { Thread.sleep(500); }catch(Exception e) { e.printStackTrace(); } endTime=System.currentTimeMillis(); repaint(); } }}
------解决方案--------------------
我帮你改了TestStopWatch,你主要是没有用setVisible将界面显示出来
- Java code
import java.awt.event.*;import java.awt.*;class TestStopWatch extends Frame{ public TestStopWatch() { this.add(new StopWatch()); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) //这里写错了,你写成WindowClosing了 { dispose(); System.exit(0); } }); } public static void main(String []args) { TestStopWatch sw=new TestStopWatch(); //下面还要加两句 sw.setSize(400, 300); sw.setVisible(true); }}