tags:

views:

226

answers:

3

When I try to run an applet in applet viewer it is not able to find resources (Image). I try to load resource like this:

String cb= this.getCodeBase().toString();
String imgPath = cb+"com/blah/Images/a.png";
System.out.println("imgPath:"+imgPath);
java.net.URL imgURL = Applet.class.getResource(path);

but when i run it in appet viewer path is like this: imgPath:file:D:/Work/app/build/classes/com/blah/Images/a.png

though image is there in this path, is prefix file: causing problem, how can i test this code?

Will this code work when deployed in server and codebase returns a server URL?

A: 

Just use /com/blah/Images/a.png as the path. getResource() is clever enough to find it.

Aaron Digulla
if i do that, loading of images fail once deployed to server
sachin
Then the image wasn't added to the JAR file which you deployed.
Aaron Digulla
The path you specify must be the one under which you can find the image in the JAR. Use "/" to tell Java to search from the root (as opposed to searching relative to `Applet.class`).
Aaron Digulla
+1  A: 

Is your applet supposed to load images after it is loaded? Or would you be better served bundling necessary image resources in the jar with your applet?

I work daily on an applet-based application with plenty of graphics in the GUI. They are bundled in the jar-file. This si what we do:

// get the class of an object instance - any object.  
// We just defined an empty one, and did everything as static.
class EmptyClass{}
Class loadClass = new EmptyClass().getClass();
// load the image and put it directly into an ImageIcon if it suits you
ImageIcon ii = new ImageIcon(loadClass.getResource("/com/blah/Images/a.png"));
// and add the ImageIcon to your JComponent or JPanel in a JLabel
aComponent.add(new JLabel(ii));

Make sure your image is actuallly in the jar where you think it is. Use:

jar -tf <archive_file_name>

... to get a listing.

Terje Dahl
I am adding images to jar file as well... in this path:/com/blah/Images/a.pnghow can i get load images in that case? also will it work if i use appet viewer?
sachin
A: 

The context classloader should work with jars.

ClassLoader cl = Thread.getContextClassLoader();
ImageIcon icon = new ImageIcon(cl.getResource("something.png"), "description");
ZombieDev