Question

I have an applet with some buttons in it, the buttons have image icons. I also have made an HTML file with this applet. Whenever I open this page from server (Apache tomcat) an exception occurs:

java.lang.reflect.InvocationTargetException.

But if I run without the icons, there are no problems. Can anyone help me, so that I can load the applet with the button icons?

Image myImage = getToolkit().createImage("image/REC1.jpg");

ImageIcon myIcon = new ImageIcon(myImage);
button.setIcon(myIcon);
Était-ce utile?

La solution

Toolkit.createImage(String):

Returns an image which gets pixel data from the specified file. The returned Image is a new object which will not be shared with any other caller of this method or its getImage variant.

This method first checks if there is a security manager installed. If so, the method calls the security manager's checkRead method with the specified file to ensure that the image creation is allowed.

I made 2 parts bold:

  • File - only ever points to the local file-system of the computer on which the applet is running. So are unsuitable for icons in the applet - they must be on the server. And..
  • Security Manager - which will not allow a sand-boxed applets to read or write to the local file-system. That might be the important part of the stack trace that is missing.

Applet resource access

Applets need to load resources from the 'home server' if sand-boxed, by URL.

The icons might be an embedded resource, inside a Jar referenced in the archive attribute of the applet element, but if they are loaded to the server as images, they can be accessed relative to the document base or code base. Here is what it might look like for an image named REC1.jpg in the image sub-directory of the directory that contains the HTML.

URL url = new URL(getDocumentBase(), "image/REC1.jpg");
Image myImage = getToolkit().createImage(url);

Autres conseils

you can use .PNG file format also. and used small letter for file name.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top