When I try to load a .gif as an ImageIcon in a JLabel in my applet, a security exception (checkread) is thrown. The same code works with appletviewer. Why does this happen and how do I correct it?

Jayaram Narayana

The problem is that applets restrict read access to the local computer. This is a security measure meant to protect your computer from attacks such as reading your files and reporting them to someone or deleting your files.

You can solve this by placing the gif in the same jar in which the applet resides or in the codebase for the applet on the webserver. (If you did not explicitly specify a codebase or archive jar on your applet tag, the codebase is considered the directory in which the HTML file resides)

However, you need to access the gif as a resource file. You can do this by calling getResource() as follows:

URL url = getClass().getResource("foo.gif");
ImageIcon icon = new ImageIcon(url);
JLabel label   = new JLabel(i);

This asks the classloader that loaded your applet to try to find the gif. It will search in either the jar file or the codebase on the web server.