How to read images from applet JAR file

I have an applet whose required files (class, gif etc) are stored in a JAR file. I want to read some images from the JAR file to be used as button icons in the applet. I wrote a method to read from the JAR file and to return the image in a ImageIcon object:

public static ImageIcon loadIcon(String name) {
   try {
      ImageIcon imageIcon = new ImageIcon(ClassLoader.getSystemResource(name));
      return imageIcon;
   } catch (Exception exception) {}
      return null;

However, it doesn't work. I have also tried adding "/" in front of "name" but still won't work. Any help is appreciated.

BTW, if I run my program as a stand-alone application, the images are read successfully from the JAR file.
Who is Participating?
objectsConnect With a Mentor Commented:
getClass().getResource(name) will work in an applet.
did you try

ImageIcon imageIcon = new ImageIcon(ClassLoader.getResource(name));

ImageIcon imageIcon =
 new ImageIcon(getClass().getResource(name));

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

yongsingAuthor Commented:
heyhey_, ClassLoader.getResource() is a non-static method. You can't call it from a static context.
yongsingAuthor Commented:
Yes, I've tried it and it works. Thanks!
no worries.
Thanks for the points :)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.