Loading images in applets (and sometimes in applications)
requires a few more code lines. The thing is that the code:
backImage = getImage(getCodeBase(), "land.gif");
doesn't get you the image right away, it has to download completely
to the client before you can display it. If you attempt to
draw it before all its bytes have arrived you'll see nothing
or just parts of it. So, you have to wait for it.
Provided that the image is really located at the applets codebase
you cold try this (I'm loading two images here just for
demonstration)
Code:
boolean imagesOK=false;
Dimension imgDimA=null;
Dimension imgDimB=null;
.
.
MediaTracker mt=new MediaTracker(this);
backImageA = getImage(getCodeBase(), "land1.gif");
mt.addImage(backImageA,0);
backImageB = getImage(getCodeBase(), "land2.gif");
mt.addImage(backImageB,1);
try {
mt.waitForAll();
} catch (InterruptedException ie) {
return; // just leave, the client probably left your page
}
imgDimA=new Dimension(backImageA.getWidth(this), backImageA.getHeight(this));
imgDimB=new Dimension(backImageB.getWidth(this), backImageB.getHeight(this));
if (imgDimA.width > 0 && imgDimA.height > 0 &&
(imgDimB.width > 0 && imgDimB.height > 0) {
imagesOK=true;
}
Another nice habit:
Code:
public void update(Graphics g) {
if (imagesOK) {
g.drawImage(backImageA, 0, 0, this);
} else {
g.drawString("Loading images",0,0);
}
}
public void paint(Graphics g) {
update(g);
}
If you are using IE, and you are not doing it already I recommend that you bring up the java console (tools->sun java console) and
check for exceptions stacktraces.
Bookmarks