2

Had no luck getting this to work via what I found on google.

user1012037
  • 501
  • 1
  • 4
  • 18
  • 1) Make sure to set the Jar entries to 'no compression' if it only contains images. Zip (as used in a Jar) compression does almost nothing for images. 2) I would recommend putting the classes into a separate Jar that uses standard compression. They will be compressed smaller and the JRE only needs to do a single connection to the server to get them all. Why do you *not* want to put the applet in a Jar? – Andrew Thompson Jan 24 '12 at 04:04

2 Answers2

3

You can load any resource that is available on the classpath, which your jar would be a part of, using ClassLoader.getResource(String)

You can obtain a reference to a relevant ClassLoader object using Class.getClassLoader()

ClassLoader cl = MyClass.class.getClassLoader();

If your image were named myimage.png and in a directory called images inside your jar, you could get the image like so.

URL url = cl.getResource("images/myimage.png");

You can then use the URL to create an image object in memory.

Image i = Toolkit.getDefaultToolkit().createImage(url);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Dev
  • 11,919
  • 3
  • 40
  • 53
  • It is best to link to the latest version of the JavaDocs. I have edited your answer to point to J2SE 7. For tips on getting a link to the latest docs, see [point 2 of advantages](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7090875). +1 for the answer. – Andrew Thompson Jan 24 '12 at 04:06
  • Thank you. Beautiful. By the way is there any analogous way to do this with audio files? Toolkit doesn't seem to cover it. – user1012037 Jan 24 '12 at 04:55
  • I recommend taking a look this question http://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java . Worth noting, If the methods you want to use don't accept a URL object but will take an `InputStream`. You can use the URL object to get a raw `InputStream` by calling the `openStream()` method on it. You could then pass this stream of bytes to whatever you need to. – Dev Jan 24 '12 at 05:01
3

The tutorial on How to Use Icons at the Java website may be of use to you.

You'll do something like this:

java.net.URL imgURL = this.getClass().getResource(path);

The getResource() method uses the same loading rules as defined by the ClassLoader for the class.

Milind Ganjoo
  • 1,260
  • 11
  • 13