简体   繁体   中英

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. 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:

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

Unfortunately, the URL object is always 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. I have also tried using the path '/images/a.png', but still the same problem. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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