Java – add image to jar
I want to set the icon to my JFrame I do the following:
Image icon = Toolkit.getDefaultToolkit().getImage("src/images/icon.jpg"); this.setIconImage(icon);
It works when I run this code from NetBeans, but when I try to run this code from a jar file, the image will not appear in my JFrame I tried to load an image as a resource:
this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/src/images/icon.jpg")));
But when I run this code, it fails with NullPointerException
Uncaught error fetching image: java.lang.NullPointerException at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:99) at sun.awt.image.URLImageSource.getDecoder(URLImageSource.java:113) at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:240) at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172) at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
How should I do this job?
Editor: Thank you for solving the problem by specifying the image as
Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("images/icon.JPG"))
As for it looks strange, it would be better if it were
this.setIconImage(new ImageIcon(pathToIcon).getImage());
Solution
Looking at the source code of urlimagesource, it seems that getconnection throws NPE because its URL is null It makes me wonder
getClass().getResource("/src/images/icon.jpg")
Return null It does this if it cannot find a resource with that pathname
I bet the problem is that you're on the wrong path
To prove / refute this, you should run jar tvf on the jar file and look for a line that matches "icon. JPG" Is the corresponding pathname the same as the pathname you used? If not, use the pathname of the matching line in the getresource call, which should work Or, if the file doesn't show up at all, check the NetBeans build configuration and tell it what to put into the jar file (I'm not a NetBeans user, so I can't say where you need to see...)
If this leads you nowhere to go, another possibility is getclass() Getresource (...) uses a classloader that does not know the jar file containing the image (this seems unlikely to me...)