1

I have an Image displayStartText and originalStartText initialized thusly:

Image originalStartText = new ImageIcon(getClass().getClassLoader().getResource( "GAME/resources/ready_set_fight.gif" )).getImage();
Image displayStartText = originalStartText;

I try to draw displayStartText centered in my background with:

g2d.drawImage( displayStartText, (int)((bgDispWidth-displayStartText.getWidth())/2), (int)((bgDispHeight-displayStartText.getHeight())/2), null );

But a compiler error that I don't understand shows up

Gameplay.java:694: error: method getWidth in class Image cannot be applied to given types;
     g2d.drawImage( displayStartText, (int)((bgDispWidth-displayStartText.getWidth())/2), (int)((bgDispHeight-displayStartText.getHeight())/2), null );
                                                                         ^
  required: ImageObserver
  found: no arguments
  reason: actual and formal argument lists differ in length

Any insights on why I might run into this issue?

hjl
  • 15
  • 6

1 Answers1

2

Image doesn't have a getWidth() method, if you look at the JavaDocs you will find that it requires a parameter of ImageObserver, because the image might not be loaded when you request the value (because of the way it works), you can use an ImageObserver to be notified when data becomes available.

All Swing components implement ImageObserver, so you could (in theory) use this if the class was Swing based object or null if you don't have one.

If you're using null, then you should ensure that the image is loaded first, using MediaTracker for example, otherwise getWidth(ImageObsever) may return -1

A better solution (IMHO) would be to use ImageIO.read which will return a BufferedImage which is gurenteed to be loaded when it returns and saves you some of these problems.

Have a look at Reading/Loading an image for more details

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366