首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Graphics.drawLine步骤出现NullPointerException

2012-12-23 
Graphics.drawLine方法出现NullPointerException点击下面标题查看本文完整版:Graphics.drawLine方法出现Nu

Graphics.drawLine方法出现NullPointerException
点击下面标题查看本文完整版:Graphics.drawLine方法出现NullPointerException

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
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->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对象供自己使用!
    

热点排行