SE450: Adapters [3/55] Previous pageContentsNext page

file:horstmann/ch10_adapter/IconAdapter.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
package horstmann.ch10_adapter;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.Icon;
import javax.swing.JComponent;

/**
   An adapter that turns an icon into a JComponent.
 */
@SuppressWarnings("serial")
public class IconAdapter extends JComponent
{
  /**
      Constructs a JComponent that displays a given icon.
      @param icon the icon to display
   */
  public IconAdapter(Icon icon)
  {
    this.icon = icon;
  }

  public void paintComponent(Graphics g)
  {
    icon.paintIcon(this, g, 0, 0);
  }

  public Dimension getPreferredSize()
  {
    return new Dimension(icon.getIconWidth(),
        icon.getIconHeight());
  }

  private Icon icon;
}

file:horstmann/ch10_adapter/IconAdapterTester.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
package horstmann.ch10_adapter;
import java.awt.BorderLayout;

import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFrame;

/**
   This program demonstrates how an icon is adapted to
   a component. The component is added to a frame.
 */
public class IconAdapterTester
{
  public static void main(String[] args)
  {
    Icon icon = new CarIcon(300);
    JComponent component = new IconAdapter(icon);

    JFrame frame = new JFrame();
    frame.add(component, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}

Previous pageContentsNext page