Java getClass()。getResource(“ file”)导致NullPointerException [英] Java getClass().getResource("file") leads to NullPointerException

查看:184
本文介绍了Java getClass()。getResource(“ file”)导致NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遵循 zetcode Snake Java游戏教程,总是会收到以下错误消息:

  ImageIcon iid = new ImageIcon(this.getClass()。getResource( ball.png)); 
ball = iid.getImage();

线程 main中的异常java.lang.NullPointerException javax.swing.ImageIcon上的
。(init>(未知源)snake2.Board上的
。 ;(Board.java:52)
在snake2.Snake。< init>(Snake.java:10)
在snake2.Snake.main(Snake.java:22)

我实际上只是复制并粘贴了代码以查看其工作原理。它们的包装也正确;但是,当我尝试运行它时,总是会遇到此错误。

解决方案

图片应位于同一包中(文件夹(以OS术语表示)作为已编译的类。检查同一文件夹中是否同时具有 .class .png 。如果没有,您可以在 getResource(..)中使用类路径相对路径,方法是从 /

I am following the zetcode Snake java games tutorial and always get this error:

ImageIcon iid = new ImageIcon(this.getClass().getResource("ball.png"));
ball = iid.getImage();

Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at snake2.Board.<init>(Board.java:52)
    at snake2.Snake.<init>(Snake.java:10)
    at snake2.Snake.main(Snake.java:22)

I actually just copied and pasted the code to see how it works. They are in the right packages too; but when I try to run it, I always end up with this error.

解决方案

The image should be in the same package (folder in OS terms) as the compiled class. Check whether you have both .class and .png in the same folder. If not, you can use classpath-relative paths in getResource(..), by starting with /

这篇关于Java getClass()。getResource(“ file”)导致NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆