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

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

问题描述

我正在关注 Snake Java 游戏教程,但总是收到此错误:

I am following the 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.

推荐答案

图像应该与编译的类位于同一个包中(操作系统术语中的文件夹).检查您是否在同一文件夹中同时拥有 .class.png.如果没有,您可以在 getResource(..) 中使用类路径相对路径,以 /

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天全站免登陆