Graphics.drawLine方法出现NullPointerException:
不知道应该怎么解释这样的问题,一个同学写的,结构有点乱
import java.awt.*;
import java.awt.event.*;
class test extends Frame
{
static Frame temp=null;
int bx,by,ex,ey;
Graphics b1=null;
public static void main(String[] args)
{
temp=new test();
new test().draw();
}
public void paint(Graphics g)
{
if(b1==null)
System.out.print("come here");
else
g.drawLine(bx,by,ex,ey);
}
public void draw()
{
temp=new Frame();
temp.setSize(200,300);
temp.setVisible(true);
temp.addMouseListener
(
new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
bx=e.getX();
by=e.getY();
}
public void mouseReleased(MouseEvent e)
{
ex=e.getX();
ey=e.getY();
b1=getGraphics();
b1.drawLine(bx,by,ex,ey);//这里出现问题,好象是graphics对象取不到参数 //b1.drawLine(1,1,2,2);改成常量也不行
}
}
);
}//draw
}//allend
------解决方法--------------------------------------------------------
代码的确写的很乱,可以下面这么解决!
import java.awt.*;import java.awt.event.*;public class Test extends Frame { static Frame temp = null; int bx, by, ex, ey; Graphics b1 = null; public static void main(String[] args) { temp = new Test(); new Test().draw(); } public void paint(Graphics g) { if (b1 == null) System.out.print("come here"); else g.drawLine(bx, by, ex, ey); } public void draw() { temp = new Frame(); temp.setSize(200, 300); temp.setVisible(true); temp.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { bx = e.getX(); by = e.getY(); } public void mouseReleased(MouseEvent e) { ex = e.getX(); ey = e.getY(); [color=#FF0000]b1 = temp.getGraphics();[/color] b1.drawLine(bx, by, ex, ey);//这里出现问题,好象是graphics对象取不到参数 //b1.drawLine(1,1,2,2);改成常量也不行 } }); }//draw }//allend
------解决方法--------------------------------------------------------
b1=getGraphics()得到的实际上是你main方法中new test()对象的Graphics
但new test()并没有调用setVisible(true),使它可见.
所以b1是null,
而你却在temp指向的对象中画的,所以要用temp.getGraphics()得到它自己的Graphics对象供自己使用!