quite a newbie here but here’s a small test code that explains my issue. The value printed is -1. I just don’t have the slightest clue on how to return the pixel width of my image, am I missing something very obvious here? This whole ImageObserver thingy makes no sense!!!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class imagetest2 extends JPanel {
Image i =Toolkit.getDefaultToolkit().getImage(/*image*/);
public int test(){
int x = i.getWidth(null);
return x;
}
}
class imagetest {
public static void main(String args[]){
imagetest2 tesst = new imagetest2();
System.out.print(tesst.test());
}
}
Toolkit.getDefaultToolkit().getImage()might asynchronously load the image which is almost never what you want.Use
ImageIOand aBufferedImageinstead which also hasgetWidth()andgetHeight()without anImageObserverparameter (although the other ones will work as well if you passnull):