免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3307 | 回复: 2
打印 上一主题 下一主题

image.getGraphics() 抛出NullPointerException异常 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-02-12 11:23 |只看该作者 |倒序浏览

  1. import java.awt.*;
  2. import javax.swing.*;

  3. public class testGraphics extends JFrame
  4. {
  5.         Graphics gra;
  6.         Image image;
  7.         public testGraphics(){
  8.                 super("test Graphics");
  9.                 image = createImage(500,500);        //创建一幅提供绘制的图片.
  10.                 gra = image.getGraphics();        //获得图片绘制对象
  11.                 setSize(500,500);
  12.                 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  13.                 setVisible(true);
  14.         }
  15.         public void paint(Graphics g){
  16.                 g.setColor(Color.red);
  17.                 g.drawString("testGraphics",100,100);
  18.         }
  19.         public static void main(String args[]){
  20.                 new testGraphics();
  21.         }
  22. };
复制代码


Exception in thread "main" java.lang.NullPointerException
        at testGraphics.<init>(gra = image.getGraphics())

不明白为何会抛出异常啊,我获得的是一个图片的绘制对象..高手指点指点哦

论坛徽章:
0
2 [报告]
发表于 2007-02-12 12:14 |只看该作者
image 对象为 null,当然抛异常

论坛徽章:
0
3 [报告]
发表于 2007-02-12 12:55 |只看该作者
明白了

关键这一句 setVisible(true);

获得容器绘图对象前必须先显示它. 不然获得的就是一个空的对象.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP