Reputation: 16038
I am making a method that returns the width and height of an image. It's an ordinary 32x32 icon. Here is what I did so far:
Image icon;
String filename = "G:\\icon.jpg";
int iconWidth = 0;
int iconHeight = 0;
icon = Toolkit.getDefaultToolkit().getImage(filename);
iconWidth = icon.getWidth(null);
iconHeight = icon.getHeight(null);
System.out.println(iconWidth);
JFrame window = new JFrame();
icon = Toolkit.getDefaultToolkit().getImage(filename);
iconWidth = icon.getWidth(null);
iconHeight = icon.getHeight(null);
System.out.println(iconWidth);
The code outputs
-1
32
32 is the correct width of the image. But why does it first return -1? The code is exactly the same. Removing the "JFrame" line makes it return two -1s. Could the JFrame be affecting the default toolkit?
I also tried this code:
JFrame window = new JFrame();
icon = Toolkit.getDefaultToolkit().getImage(filename);
iconWidth = icon.getWidth(null);
iconHeight = icon.getHeight(null);
System.out.println(iconWidth);
It also returns -1. I simply can't understand why I have to call it twice to get a correct result.
Upvotes: 0
Views: 918
Reputation: 1500785
From the docs for getWidth
:
Determines the width of the image. If the width is not yet known, this method returns -1 and the specified
ImageObserver
object is notified later.
So perhaps the image is still being loaded asynchronously. Try using an ImageObserver so you can be notified when the information becomes available.
Upvotes: 4