示例#1
0
  /**
   * Gets the image using the specified dimension.
   *
   * @param d The <code>Dimension</code> of the requested image. Rescaling will be performed if
   *     necessary.
   * @return The <code>Image</code> with the required dimension.
   */
  public Image getImage(Dimension d) {
    final Image im = getImage();
    if (im == null || (im.getWidth(null) == d.width && im.getHeight(null) == d.height)) return im;

    synchronized (loadingLock) {
      final Image cached = scaledImages.get(d);
      if (cached != null) return cached;

      MediaTracker mt = new MediaTracker(_c);
      try {
        // Use SCALE_REPLICATE instead of SCALE_SMOOTH to avoid
        // ClassCastException.
        // TODO (perhaps): find a better solution.
        Image scaled = im.getScaledInstance(d.width, d.height, Image.SCALE_REPLICATE);
        mt.addImage(scaled, 0, d.width, d.height);
        mt.waitForID(0);
        int result = mt.statusID(0, false);
        if (result == MediaTracker.COMPLETE) {
          scaledImages.put(d, scaled);
        } else {
          logger.warning("Scaling image: " + getResourceLocator() + " => " + result);
        }
        return scaled;
      } catch (Exception e) {
        logger.log(Level.WARNING, "Failed to scale image: " + getResourceLocator(), e);
      }
    }
    return null;
  }
示例#2
0
 /** Preload the image. */
 public void preload() {
   synchronized (loadingLock) {
     if (image == null) {
       MediaTracker mt = new MediaTracker(_c);
       Image im;
       try {
         // Explicitly check that the URI is valid before
         // letting createImage go off and look for it, as the
         // error it throws is cryptic.
         URL url = getResourceLocator().toURL();
         InputStream is = url.openStream();
         is.close();
         im = Toolkit.getDefaultToolkit().createImage(url);
         mt.addImage(im, 0);
         mt.waitForID(0);
         if (mt.statusID(0, false) == MediaTracker.COMPLETE) {
           image = im;
         }
       } catch (Exception e) {
         logger.log(Level.WARNING, "Failed to load image from: " + getResourceLocator(), e);
       }
     }
   }
 }