专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Java Exception

Graphics.drawLine方法出现NullPointerException

发布时间:2010-06-05 12:19:16 文章来源:www.iduyao.cn 采编人员:星星草

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



------解决方法--------------------------------------------------------
代码的确写的很乱,可以下面这么解决!

Java code


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对象供自己使用!

    
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: