SE450: Proxies [28/55] Previous pageContentsNext page

file:horstmann/ch10_proxy/ImageProxy.java [source] [doc-public] [doc-private]
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;
}

file:horstmann/ch10_proxy/ProxyTester.java [source] [doc-public] [doc-private]
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
package horstmann.ch10_proxy;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;

/**
   This program demonstrates the use of the image proxy.
   Images are only loaded when you press on a tab.
 */
public class ProxyTester
{
  public static void main(String[] args)
  {
    JTabbedPane tabbedPane = new JTabbedPane();
    for (String name : imageNames)
    {
      JLabel label = new JLabel(new ImageProxy(name));
      tabbedPane.add(name, label);
    }

    JFrame frame = new JFrame();
    frame.add(tabbedPane);

    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }

  private static final String[] imageNames =
    {
        "devonian.gif",
        "permian.gif",
        "jurassic1.gif",
        "jurassic2.gif",
        "cretaceous1.gif",
        "cretaceous2.gif",
        "cretaceous3.gif",
        "eocene1.gif",
        "eocene2.gif",
        "oligocene.gif",
        "miocene.gif",
        "pleistocene.gif"
    };

  private static final int FRAME_WIDTH = 500;
  private static final int FRAME_HEIGHT = 300;
}

Previous pageContentsNext page