[英]NullPointerException when using a classLoader for loading an ImageIcon
为什么在使用 ClassLoader 时会出现 nullPointerException
ClassLoader cl = ClassLoader.getSystemClassLoader();
ImageIcon img = new ImageIcon(cl.getResource("logo.png"));
根据 Eclipse,NullPointerException 位于创建 imageIcon 的同一行
图像在那里,因为以下工作正常:
ImageIcon img = new ImageIcon("logo.png");
我正在使用类加载器,因为我想将它包含在一个可执行的 jar 中。
Eclipse 资源管理器中的项目。 主要功能在 Gui.java 中
ClassLoader cl = ClassLoader.getSystemClassLoader();
cl
是null
,因为你从引导类加载器调用它,根据java 的 api :
获取类加载器
public ClassLoader getClassLoader()
一些实现可能使用 null 来表示引导类加载器。 如果此类由引导类加载器加载,则此方法将在此类实现中返回 null。
由于cl
为空,这就是您的代码在使用时抛出NullPointerException
的原因。
做如下
ClassLoader cl = this.getClass().getClassLoader();
ImageIcon img = new ImageIcon(cl.getResource("logo.png"));
这可能是一个有点脏的解决方案 - 但我试图将图像放入 bin 文件夹中,然后它就可以正常工作了!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.