Load an Image from a JAR fileTag(s): AWT
[JDK1.1 application]
String imgName = "image.jpg";
URL imgURL = getClass().getResource(imgName);
Toolkit tk = Toolkit.getDefaultToolkit();
Image img = null;
try {
MediaTracker m = new MediaTracker(this);
img = tk.getImage(imgURL);
m.addImage(img, 0);
m.waitForAll();
}
catch (Exception e) {
e.printStackTrace();
}Because of some security reason, it's not possible with some browser (like Netscape) to use the getResource() method from an Applet. Instead we must use the getResourceAsStream method.
Image img = null;
try {
MediaTracker m = new MediaTracker(this);
InputStream is = getClass().getResourceAsStream("image.gif");
//
// if your image is in a subdir in the jar then
// InputStream is = getClass().getResourceAsStream("img/image.gif");
// for example
//
BufferedInputStream bis = new BufferedInputStream(is);
// a buffer large enough for our image
//
// can be
// byte[] byBuf = = new byte[is.available()];
// is.read(byBuf); or something like that...
byte[] byBuf = = new byte[10000];
int byteRead = bis.read(byBuf,0,10000);
img = Toolkit.getDefaultToolkit().createImage(byBuf);
m.addImage(img, 0);
m.waitForAll();
}
}
catch(Exception e) {
e.printStackTrace();
}URL url = this.getClass().getResource("myIcon.gif");
button.setIcon(new ImageIcon(url));
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com