SE450: Filling Shapes [35/41] Previous pageContentsNext page

.

file:horstmann/ch04_icon3/CarIcon.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

package horstmann.ch04_icon3;
import java.awt.Color;
import java.awt.Component;
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;

/**
   An icon that has the shape of a car.
 */
public class CarIcon implements Icon
{
  /**
      Constructs a car of a given width.
      @param aWidth the width of the car
   */
  public CarIcon(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);

    // The bottom of the front windshield
    Point2D.Double r1
    = new Point2D.Double(x + width / 6, y + width / 6);
    // The front of the roof
    Point2D.Double r2
    = new Point2D.Double(x + width / 3, y);
    // The rear of the roof
    Point2D.Double r3
    = new Point2D.Double(x + width * 2 / 3, y);
    // The bottom of the rear windshield
    Point2D.Double r4
    = new Point2D.Double(x + width * 5 / 6, y + width / 6);

    Line2D.Double frontWindshield
    = new Line2D.Double(r1, r2);
    Line2D.Double roofTop
    = new Line2D.Double(r2, r3);
    Line2D.Double rearWindshield
    = new Line2D.Double(r3, r4);

    g2.fill(frontTire);
    g2.fill(rearTire);
    g2.setColor(Color.red);
    g2.fill(body);
    g2.draw(frontWindshield);
    g2.draw(roofTop);
    g2.draw(rearWindshield);
  }

  private int width;
}


Previous pageContentsNext page