001package horstmann.ch10_proxy;
002import java.awt.Component;
003import java.awt.Graphics;
004
005import javax.swing.Icon;
006import javax.swing.ImageIcon;
007
008/**
009   A proxy for delayed loading of image icons.
010 */
011public class ImageProxy implements Icon
012{
013        /**
014      Constructs a proxy for delayed loading of an image file.
015      @param name the file name
016         */
017        public ImageProxy(String name)
018        {
019                this.name = name;
020                image = null;
021        }
022
023        public void paintIcon(Component c, Graphics g, int x, int y)
024        {
025                ensureImageLoaded();
026                image.paintIcon(c, g, x, y);
027        }
028
029        public int getIconWidth()
030        {
031                ensureImageLoaded();
032                return image.getIconWidth();
033        }
034
035        public int getIconHeight()
036        {
037                ensureImageLoaded();
038                return image.getIconHeight();
039        }
040
041        /**
042      Loads the image if it hasn't been loaded yet. Prints
043      a message when the image is loaded.
044         */
045        private void ensureImageLoaded()
046        {
047                if (image == null)
048                {
049                        System.out.println("Loading " + name);
050                        image = new ImageIcon(name);
051                }
052        }
053
054        private String name;
055        private ImageIcon image;
056}