我正在编写一个小应用程序,当我尝试创建一个ImageIcon时,我总是遇到异常.这个例外代码引起了异常:
prayerLevel.setIcon(new ImageIcon(getClass().getResource("/icons/icon_prayer.png")));
Run Code Online (Sandbox Code Playgroud)
现在在我的程序中,文件夹/ icons /确实存在.我不知道它是否有所不同但是类文件在一个包中,其中icons文件夹在项目文件夹中(当你看到bin和src文件夹时).
我已经四处寻找,我找不到可以帮助我解决问题的解决方案.也许你们中的任何人都可以帮忙吗?
编辑:有人要求我的文件夹层次结构:

我知道类文件与图标不在同一个文件夹中,但我已经创建了应用程序,我必须从不同的文件夹加载文件并执行/文件夹/始终用于工作.
编辑2:
System.out.println(getClass().getResource("/icons/icon_prayer.png") == null);
Run Code Online (Sandbox Code Playgroud)
打印真实.
Nat*_* W. 11
我相信NPE正在从ImageIcon构造函数中抛出,就像getResource返回一样null.
请尝试以下方法:
getClass().getClassLoader().getResource("/icons/icon_prayer.png")
Run Code Online (Sandbox Code Playgroud)
要么:
ClassLoader.getSystemResource("/icons/icon_prayer.png")
Run Code Online (Sandbox Code Playgroud)