[code=Java][/code]
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
public class StopWatch extends Canvas implements Runnable {
private long startTime=0;
private long endTime=0;
private boolean bStart =false;
public StopWatch(){
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
setSize(300,200);
}
protected void processMouseEvent(MouseEvent e){
if (e.getID() == MouseEvent.MOUSE_PRESSED) {
bStart = true;
new Thread(this).start();
startTime = endTime =System.currentTimeMillis();
repaint();
}else if (e.getID() == MouseEvent.MOUSE_RELEASED) {
endTime = System.currentTimeMillis();
repaint();
bStart = false;
}
}
public void paint(Graphics g){
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date elapseTime =null;
try {
elapseTime =sdf.parse("00:00:00");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
elapseTime.setTime(endTime-startTime+elapseTime.getTime());
g.draw3DRect(50, 50, 300, 100, true);
// g.drawRect(45, 45, 400, 150);
g.setFont(new Font("斜体", Font.ITALIC, 30));
g.setColor(Color.red);
String display = sdf.format(elapseTime);
g.drawString(display, 150, 100);
}
public void run(){
while (bStart) {
try {
Thread.sleep(300);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
endTime = System.currentTimeMillis();
repaint();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
StopWatch sw = new StopWatch();
Frame f = new Frame();
f.add(new StopWatch());
f.setSize(800, 800);
f.setVisible(true);
}
}
请问为什么我把main函数中的代码“
Frame f = new Frame();
f.add(new StopWatch());
f.setSize(800, 800);
f.setVisible(true);
”
放在构造函数“public StopWatch(){
code..
}”就出现问题了,这是为什么哈!问题补充:
我突然想到是“递归”造成的死循环?请问,我是理解对还是不对?
------解决方案--------------------------------------------------------
- Java code
Frame f = new Frame(); f.add([color=#FF0000]new StopWatch()[/color]); f.setSize(800, 800); f.setVisible(true); }
------解决方案--------------------------------------------------------
“我突然想到是“递归”造成的死循环?请问,我是理解对还是不对?”
我觉得楼主理解的对!我也认为是递归造成的。
------解决方案--------------------------------------------------------
public static void main(String[] args) {
// TODO Auto-generated method stub
StopWatch sw = new StopWatch();
Frame f = new Frame();
f.add(new StopWatch());
f.setSize(800, 800);
f.setVisible(true);
}
假设你放在构造里
分析一下这个代码,先实例化一个StopWatch ,然后实例化Frame ,然后你调用 f.add(new StopWatch());
这个方法,你有没有发现,你又重新实例化了StopWatch 然后又要进入构造方法里,又去实例化Frame ,一直在操作这样的动作
------解决方案--------------------------------------------------------
是OutOfMemory吗?