tags:

views:

98

answers:

4

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?

+2  A: 

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.

Thomas Owens
But the image is displayed, so how can it be that the size cannot be known? It simply does not make any sense. I add the image, it is displayed, yet the methods still return -1.
Fred
Perhaps you should add some code to your question, then, so everyone can see what you are trying to do.
Thomas Owens
http://pastebin.com/m2688ed89 and http://pastebin.com/m1b83f8a7.The first one is my Background class, simply a JPanel that displays an image. It takes an imagepath.The second one is my program. Press "Arkiv", then "Ny", choose an image and watch as it is displayed into the CENTER. However, the JFrames path() does not react to this (it doesnt resize the JFrame), because somehow, the Bakgrund bg's size cannot be known. How can I solve this? I need to be able to get that Bakgrund bg's size in order to resize the JFrame to accomodate the picture.
Fred
A: 

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).

Platinum Azure
any ideas? see comments above, pastebinned the classes.
Fred
A: 

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);
}
Devon_C_Miller
For whatever reason, this worked: http://pastebin.com/m26fd0ec9the change is in the ImageIcon part.Thank yall for your help though!
Fred
A: 

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.

[]]

Carlos Heuberger