how an icon is adapted to a component : JComponent « Swing « Java Tutorial






import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

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


public class IconAdapterTester {
  public static void main(String[] args) {
    Icon icon = new MyIcon(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);
  }
}


class IconAdapter extends JComponent {
  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;
}

class MyIcon implements Icon {
  public MyIcon(int aWidth) {
    width = aWidth;
  }

  public int getIconWidth() {
    return width;
  }

  public int getIconHeight() {
    return width / 2;
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g;
    Rectangle2D.Double body = new Rectangle2D.Double(x, y + width / 6,
        width - 1, width / 6);
    Ellipse2D.Double frontTire = new Ellipse2D.Double(x + width / 6, y + width
        / 3, width / 6, width / 6);
    Ellipse2D.Double rearTire = new Ellipse2D.Double(x + width * 2 / 3, y
        + width / 3, width / 6, width / 6);


    g2.fill(frontTire);
    g2.fill(rearTire);
    g2.setColor(Color.BLACK);
    g2.fill(body);
  }

  private int width;
}








14.2.JComponent
14.2.1.JComponent
14.2.2.HTML formatting by setting the text on a labelHTML formatting by setting the text on a label
14.2.3.Listening to Inherited Events of a JComponent from Container and Component
14.2.4.Painting JComponent ObjectsPainting JComponent Objects
14.2.5.how an icon is adapted to a component
14.2.6.A Swing component that computes and displays a fractal image known as a 'Julia set'
14.2.7.Extends JComponent to create drawing pad
14.2.8.A panel that displays a paint sample.