Link to home
Start Free TrialLog in
Avatar of JavaSlave
JavaSlave

asked on

How to pack class and resource(image) in a execute-Jar file?

 I want to pack all my class files and its resource within a execute Jar file. But my program can't access the resource file(image) in the same file.

ImageIcon icon = new ImageIcon("image\\a.gif");

  The image folder is same with my class file package folder. "com". It works properly if I don't put those in a jar file. Please tell me how to solve the problem. Thank you.
Avatar of Kit_
Kit_
Flag of Russian Federation image


Try the following

Icon icon = new ImageIcon(YourClass.class.getResource("image/a.gif"))
Avatar of s_lavie
s_lavie

Or:
ImageIcon icon = new ImageIcon(((URLClassLoader)getClass().getClassLoader()).findResource("image/a.gif"));
Avatar of Mick Barry
You'd be better off not casting the class loader instance as the class loader may not necessarily be a URLClassLoader.

The getClassLoader() method may in fact return null in some instances so using the Class's getResource() method is probably a bit safer.

Another option is to use the system class loader:

ClassLoader.getSystemResource(resoucename);
objects,
> ... class loader may not necessarily be
a URLClassLoader.
I agree, but
> The getClassLoader() method may in fact return null in some instances
Can you give an example?
From the javadoc for getClassLoader:

Returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.
Avatar of JavaSlave

ASKER

Hi everybody,
  Thank for all of your comments. But I still can't see the image in my program.

  My Jar file contains 2 folder :
com/java/a.class
image/a.gif

  All method above I have tried. Hmmm... There has something I miss? Please give me more comments. Thank you.
Do you include the jar file in your classpath?
Try:

new ImageIcon(a.class.getResource("/image/a.gif"))
ASKER CERTIFIED SOLUTION
Avatar of Kit_
Kit_
Flag of Russian Federation image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank Kit, :-) the path is case-sensitive?
Not at all :)
I think, yes. But not sure.
It's ok. Thank you.
I had the same problem, Kit's suggestion worked great,.. thanks Kit