Hey all,
I had a need to load images and paint them under CrEme. As such I figured out all the code. But I have
realised that this is a common question, so thought I would post some code snippets to assist in various areas.
The first is loading the image. As we are not an applet, we don't have access to the applet load image
features. The way to do this is:
Image image = Toolkit.getDefaultToolkit().getImage(filename);
To draw the image one does:
if(image != null) {
g.drawImage(image, 0, 0, this);
}
The above code is dependant on
this being a
java.awt.component.
Now the tricky bit is when you need the image size. The image size requires a Tracker to determine
the image load time. This is a pain because under CrEme you are not an applet, therefore the image
load time shouldn't be an issue. However you can setup the Tracker to pause until loaded, and this
equals no delay for the gui. The code to do this is:
ImageObserver imageObserver;
transient int loadStatus = 0;
protected final static Component component = new Component() {};
protected final static MediaTracker tracker = new MediaTracker(component);
private Dimension calculateImageSize(Image image) {
int id = getNextId();
tracker.addImage(image, id);
try {
tracker.waitForID(id, 0);
} catch (InterruptedException e) {
System.out.println("INTERRUPTED while loading Image");
}
loadStatus = tracker.statusID(id, false);
tracker.removeImage(image, id);
Dimension d = new Dimension();
d.width = image.getWidth(imageObserver);
d.height = image.getHeight(imageObserver);
return d;
}
The above code I obtained from somewhere else and tweaked a little. Not sure where it came from
originaly, so no offence please if I am not giving due credit.
Hope that helps. When I get a chance I'll write a quick image label class for 1.1.x and post it here.
James.