I hope I'm not beating a dead horse, but it's necessary to use URLs, not Files, to identify resources like images so that your program works whether it is zipped in a jar or not. Avoid constructor ImageIcon(
String filename), since it assumes the parameter is a file system path. If the image is in the same folder as file X.class (whether that folder is in the file system or a "folder" in a jar file), the following will work:
URL url = X.class.getResource("sample.jpeg");
Icon icon = new ImageIcon(url);
But it's better to separate resources from code, so suppose we have the organization:
C:\blahblah\SampleProject\com\acme\widget\X.class
C:\blahblah\SampleProject\images\sample.jpeg
class X is in package com.acme.widget. When we zip this up in a jar, there should be paths within the jar:
/com/acme/widget/X.class
/images/sample.jar
In either case the code that works will be:
URL url = X.class.getResource("/images/sample.jpeg"); //note initial slash
Icon icon = new ImageIcon(url);
(You can always use forward slashes in URLs.) If you run this on unzipped code the URL expands to
file:/C:/blahblah/SampleProject/images/sample.jpeg
If you run this on the jar file mentioned, the URL might expand to
jar:file:/C:/elsewhere/app.jar!/images/sample.jpeg
So when the code is in a jar, "/images/sample.jpeg" denotes a "path" in the jar file and when the code isn't zipped, "/images/sample.jpeg" extends the folder that contains the start of the package hierarchy. That sounds more complicated than it really is. Once you've set things up (and I prefer using
Ant), it's a snap.