2 Replies Latest reply: Jun 5, 2009 2:06 AM by 843851 RSS

    Image and ImageObserver concepts

    843851
      Hello,
      I'm using the class Image to do buttons backgrounds, I neet get the width and height from the Image, I used the methods getWidth(ImageObserver io) and getHeight(ImageObserver io), but the first time I use one of them, the result is -1 and the others calls returns the correct value. I don't understand this. When I call this methods, I don't pass an ImageObserver (null). Somebody can explain me why? And how I can do it works correctly?

      Thank you.
        • 1. Re: Image and ImageObserver concepts
          843851
          Hello,

          it is because an image is being rendered when it is used for the first time. To force image loading you should use MediaTracker object:
          MediaTracker mediaTracker = new MediaTracker(ANY_COMPONENT);
          
          ...
          
          Image image = Toolkit.getDefaultToolkit().createImage("IMAGE_FILE_NAME");
          
          //and now:
          mediaTracker.addImage(image, 1);
          try {
            mediaTracker.waitForAll();
          } catch (final InterruptedException e) {
          }
          //after that image.getWidth(null) will return correct image's width
          Please note: After that mediaTracker is keeping a reference to this image, therefore when you would like to release resources (memory) used by image you should call
          mediaTracker.removeImage(image);
          • 2. Re: Image and ImageObserver concepts
            843851
            Thank you for explain me. Your explanation was helpful.