当前位置: 代码迷 >> Java相关 >> [讨论][原创]大家进来指点一下
  详细解决方案

[讨论][原创]大家进来指点一下

热度:257   发布时间:2006-02-12 10:22:00.0
[讨论][原创]大家进来指点一下

import java.awt.*;
import java.awt.event.*;
import java.util.*;

class draw extends Frame
{
int begX = 0;
int begY = 0;
int endX = 0;
int endY = 0;
draw(String name)
{
super(name);
this.addWindowListener
(
new WindowAdapter()
{

public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0);
}
}
);

this.addMouseListener
(
new MouseAdapter()
{


public void mousePressed(MouseEvent e)
{
begX = e.getX();
begY = e.getY();
}

public void mouseReleased(MouseEvent e)
{
Graphics gra = getGraphics();//放在这里可以
endX = e.getX();
endY = e.getY();
gra.drawLine(begX,begY,endX,endY);
}
}
);
}

public static void main(String [] args)throws Exception
{
draw f = new draw("hehe");
f.setSize(400,400);
f.setVisible(true);
}
}

这个程序的功能是在窗口上划线,这样写是对的,为什么我把上面的窗口声明语句:"Graphics gra = getGraphics();"放到外面定义,在编译的时候不会出错,但是运行的时候,鼠标一点击就会出来一大堆异常?
变成以下的就会报异常

import java.awt.*;
import java.awt.event.*;
import java.util.*;

class draw extends Frame
{
int begX = 0;
int begY = 0;
int endX = 0;
int endY = 0;
draw(String name)
{
super(name);
this.addWindowListener
(
new WindowAdapter()
{

public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0);
}
}
);

this.addMouseListener
(
new MouseAdapter()
{

Graphics gra = getGraphics();//放到这里就不行
public void mousePressed(MouseEvent e)
{
begX = e.getX();
begY = e.getY();
}

public void mouseReleased(MouseEvent e)
{

endX = e.getX();
endY = e.getY();
gra.drawLine(begX,begY,endX,endY);
}
}
);
}

public static void main(String [] args)throws Exception
{
draw f = new draw("hehe");
f.setSize(400,400);
f.setVisible(true);
}
}


----------------解决方案--------------------------------------------------------
  相关解决方案