I'd like to modify the following code so that it will load the images for the applet from the JAR file:
public static ImageIcon loadImageIcon(Applet applet, String filename)
throws MalformedURLException
{
URL url;
try {
url = new URL(applet.getCodeBase(), filename);
} catch(MalformedURLExceptio
throw (new MalformedURLException());
}
return new ImageIcon(url);
}
I have tried using the constructor URL(String filename), giving a relative path to the images which did not work.
Thanks.
?
fontaineAccepted Solution on 1998-09-08 at 08:18:51ID: 1223545
Use the following sample code as a starting point.
ream(filen ame); ).createIm age(bytes, 0, count);
public static ImageIcon loadImageIcon(String filename) {
Image image = null;
try {
// get a stream to read the image
InputStream in = getClass().getResourceAsSt
// buffering -> more efficient
BufferedInputStream bufIn = new BufferedInputStream(in);
// the byte array that will contain the image
byte bytes[] = new byte[10000];
// read the image
int count = bufIn.read(bytes, 0, 10000);
// create the image from the byte array
image = Toolkit.getDefaultToolkit(
} catch(Exception e) {
// gasp, we had a problem...
}
if (image != null) {
// build up the ImageIcon
return new ImageIcon(image);
}
return null;
}
Note: we do not use getResource() instead of getResourceAsStream() because some
browsers do not allow it, for security reasons. I have assumed that ImageIcon was the
ImageIcon class from Swing.