I have an Image img that, when trying to use any of above mentioned get methods, returns -1. Why is this? And what is an ImageObserver object?
According to the documentation for Image, these methods return a -1 if the size, width, or height (respectively) are not yet known.
Also, ImageObserver is simply an interface that provides methods to get notifications about the information of an Image object that is being constructed.
According to the Java docs, it seems that if you call getHeight() etc. on an Image while it's still in the construction phase, such that the height is not really "known", -1 is returned and the ImageObserver provided is notified.
ImageObserver is an interface that provides a way for you to have a callback method that is called when the image is updated in some way. ImageObserver is implemented by java.awt.Component, so if you extend that in the containing class you could override imageUpdated() and store the image height when the function is called asynchronously (if Image.getHeight returns -1).
In GraphTest, override imageUpdate:
@Override
public void imageUpdate(Image img, int flags,
int x, int y, int width, int height) {
if ((flags & (WIDTH|HEIGHT)) == (WIDTH|HEIGHT)) {
// width and height have meaningful values, do your resize here
}
super.imageUpdate(img, flags, x, y, width, height);
}
The problem is the time needed to load the Image.
As long as the image is not loaded you get the -1. When the image is finally loaded, it fires the ImageObserver. The obeserver, in your case the Background instance - g.drawImage(bkg, 0, 0, this); - will force a repaint of the Background causing the now loaded image to be painted.
You can also use the java.awt.MediaTracker to track the status of your Image.
[]]