01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package horstmann.ch10_proxy;
import java.awt.Component;
import java.awt.Graphics;

import javax.swing.Icon;
import javax.swing.ImageIcon;

/**
   A proxy for delayed loading of image icons.
 */
public class ImageProxy implements Icon
{
  /**
      Constructs a proxy for delayed loading of an image file.
      @param name the file name
   */
  public ImageProxy(String name)
  {
    this.name = name;
    image = null;
  }

  public void paintIcon(Component c, Graphics g, int x, int y)
  {
    ensureImageLoaded();
    image.paintIcon(c, g, x, y);
  }

  public int getIconWidth()
  {
    ensureImageLoaded();
    return image.getIconWidth();
  }

  public int getIconHeight()
  {
    ensureImageLoaded();
    return image.getIconHeight();
  }

  /**
      Loads the image if it hasn't been loaded yet. Prints
      a message when the image is loaded.
   */
  private void ensureImageLoaded()
  {
    if (image == null)
    {
      System.out.println("Loading " + name);
      image = new ImageIcon(name);
    }
  }

  private String name;
  private ImageIcon image;
}