Source of CarIcon.java


  1: import java.awt.*;
  2: import java.awt.geom.*;
  3: import javax.swing.*;

  5: /**
  6:    An icon that has the shape of a car.
  7: */
  8: public class CarIcon implements Icon
  9: {
 10:    /**
 11:       Constructs a car of a given width.
 12:       @param width the width of the car
 13:    */
 14:    public CarIcon(int aWidth)
 15:    {
 16:       width = aWidth;
 17:    }
 18:    
 19:    public int getIconWidth()
 20:    {
 21:       return width;
 22:    }

 24:    public int getIconHeight()
 25:    {
 26:       return width / 2;
 27:    }

 29:    public void paintIcon(Component c, Graphics g, int x, int y)
 30:    {
 31:       Graphics2D g2 = (Graphics2D) g;
 32:       Rectangle2D.Double body
 33:          = new Rectangle2D.Double(x, y + width / 6, 
 34:             width - 1, width / 6);
 35:       Ellipse2D.Double frontTire
 36:          = new Ellipse2D.Double(x + width / 6, y + width / 3, 
 37:             width / 6, width / 6);
 38:       Ellipse2D.Double rearTire
 39:          = new Ellipse2D.Double(x + width * 2 / 3, y + width / 3,
 40:             width / 6, width / 6);

 42:       // The bottom of the front windshield
 43:       Point2D.Double r1
 44:          = new Point2D.Double(x + width / 6, y + width / 6);
 45:       // The front of the roof
 46:       Point2D.Double r2
 47:          = new Point2D.Double(x + width / 3, y);
 48:       // The rear of the roof
 49:       Point2D.Double r3
 50:          = new Point2D.Double(x + width * 2 / 3, y);
 51:       // The bottom of the rear windshield
 52:       Point2D.Double r4
 53:          = new Point2D.Double(x + width * 5 / 6, y + width / 6);

 55:       Line2D.Double frontWindshield
 56:          = new Line2D.Double(r1, r2);
 57:       Line2D.Double roofTop
 58:          = new Line2D.Double(r2, r3);
 59:       Line2D.Double rearWindshield
 60:          = new Line2D.Double(r3, r4);

 62:       g2.fill(frontTire);
 63:       g2.fill(rearTire);
 64:       g2.setColor(Color.red);
 65:       g2.fill(body);
 66:       g2.draw(frontWindshield);
 67:       g2.draw(roofTop);
 68:       g2.draw(rearWindshield);
 69:    }

 71:    private int width;
 72: }