简体   繁体   English

访问.jar文件中的图像文件时出现NullPointerException

[英]NullPointerException when accessing image files in a .jar file

I have pretty much tried everything but still have this same problem. 我几乎尝试了一切,但仍然有同样的问题。 I have the following setup: I have a images.jar containing a folder called 'images' in which there are multiple image files. 我有以下设置:我有一个images.jar包含一个名为'images'的文件夹,其中有多个图像文件。 I add images.jar to the java build path of the project in eclipse, and i've been trying to use the following code to access the individual images in the jar: 我将images.jar添加到eclipse中项目的java构建路径中,并且我一直在尝试使用以下代码来访问jar中的各个图像:

URL url = this.getClass().getResource("images/a.png");
ImageIcon icon = new ImageIcon (url);

Unfortunately, the URL object is always NULL. 不幸的是,URL对象始终为NULL。 I don't think this has anything to do with where I put images.jar file as it is added to the classpath in eclipse. 我不认为这与我放置images.jar文件的位置有关,因为它被添加到eclipse中的类路径中。 I have also tried using the path '/images/a.png', but still the same problem. 我也试过使用路径'/images/a.png',但仍然是同样的问题。 Any suggestion would be extremely welcome! 任何建议都将非常受欢迎! Thanks. 谢谢。

Try this: 试试这个:

URL url = this.getClass().getClassLoader().getResource("images/a.png");
ImageIcon icon = new ImageIcon(url);

Without getClassLoader() invocation you are only able to access resources in JAR file where the code is stored. 如果没有getClassLoader()调用,您只能访问存储代码的JAR文件中的资源。

我无法重现你的问题,但我的理论是你从不同的地方运行这个类 - 你的图像和类在不同的jar中,或者直接从类文件中读取类。

此链接中的捆绑图像部分可能会有所帮助: http//leepoint.net/notes-java/GUI-lowlevel/graphics/45imageicon.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM