java.awt.Image getWidth and getHeight methods not working well?

I'm trying to display images which happen to be instances of the Image class (http://docs.oracle.com/javase/7/docs/api/java/awt/Image.html).I need to have it a BufferedImage and I found a piece of code that works well for that purpose (using Graphics).However to create the BufferedImage I need to know the width and height of the image. The Image class does have getWidth and getHeight methods but they don't seem to work properly all the time. Using debug I found out that sometimes, the width and height were set to -1. I also found out that actually calling getWidth and getHeight methods "updates" the width and height value, so the height and width have correct values after then. So I added a fake "image.getWidth(null)" before calling getWidth and getHeight "for real" and got the right values.That works fine when I do it in debug mode and step by step, BUT it doesn't work well anymore when I run it normally. I added a "Thread.sleep(5);" after the "fake" getWidth call and it made it work. This behaviour is quite weird and maybe someone would have an explanation and/or a way to make it work without that sleep trick ?
 
Top