为什么在使用ClassLoader
时会出现nullPointerExceptionClassLoader cl = ClassLoader.getSystemClassLoader();
ImageIcon img = new ImageIcon(cl.getResource("logo.png"));
根据Eclipse,NullPointerException是在创建imageIcon的同一行上
图片 ,因为以下工作正常:
ImageIcon img = new ImageIcon("logo.png");
我正在使用类加载器,因为我想将它包含在可执行jar中。
Eclipse浏览器中的项目。主要功能在Gui.java
答案 0 :(得分:2)
ClassLoader cl = ClassLoader.getSystemClassLoader();
cl
是null
,因为你根据java's api从bootstrap类加载器调用它:
<强> getClassLoader 强>
public ClassLoader getClassLoader()
某些实现可能使用null来表示引导类加载器。此方法将返回null 在这种实现中,如果此类由引导程序加载 类加载器。
由于cl
为空,因此您的代码在使用时会抛出NullPointerException
。
答案 1 :(得分:0)
按照以下方式执行
ClassLoader cl = this.getClass().getClassLoader();
ImageIcon img = new ImageIcon(cl.getResource("logo.png"));
答案 2 :(得分:0)
这可能是一个有点脏的解决方案 - 但我试图将图像放在bin文件夹中然后它工作得很好!!!