Java:来自class.getResource(...)的NullPointerException [英] Java: NullPointerException from class.getResource( ... )

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

问题描述

我正在编写一个小应用程序,当我尝试创建一个ImageIcon时,我总是遇到异常。这个例外代码引起了异常:

I was writing a small application and when I tried to create an ImageIcon I always got an exception. The exception was caused by this line of code:

prayerLevel.setIcon(new ImageIcon(getClass().getResource("/icons/icon_prayer.png")));

现在我的程序中,文件夹/ icons /确实存在。我不知道它是否有所不同但是类文件在一个包中,其中icons文件夹在项目文件夹中(当你看到bin和src文件夹时)。

Now within my program, the folder /icons/ does exist. I don't know if it makes the difference but the class file is within a package, where as the icons folder is within the project folder (when you would see the bin and src folder).

我已经四处寻找,我找不到可以帮助我解决问题的解决方案。也许你们中的任何人都可以提供帮助?

I have looked around for a bit and I couldn't find a solution that could help me solve the problem. Perhaps any of you guys could help?

编辑:有人要求我的文件夹层次结构:

someone asked for my folder hierarchy:

我知道类文件不在同一个文件夹作为图标,但我已经创建了应用程序,我必须从不同的文件夹加载文件和/文件夹/总是用来工作。

I know the class file is not in the same folder as the icons are, but I've made applications where I had to load files from a different folder and doing /folder/ always used to work.

编辑2:

System.out.println(getClass().getResource("/icons/icon_prayer.png") == null);

打印为真。

推荐答案

我相信NPE是从 ImageIcon 构造函数抛出的,因为 getResource 正在返回

I believe the NPE is being thrown from the ImageIcon constructor as getResource is returning null.

尝试以下方法:

getClass().getClassLoader().getResource("/icons/icon_prayer.png")

或:

ClassLoader.getSystemResource("/icons/icon_prayer.png")

这篇关于Java:来自class.getResource(...)的NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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