001
002package horstmann.ch04_icon3;
003import java.awt.Color;
004import java.awt.Component;
005import java.awt.Graphics;
006import java.awt.Graphics2D;
007import java.awt.geom.Ellipse2D;
008import java.awt.geom.Line2D;
009import java.awt.geom.Point2D;
010import java.awt.geom.Rectangle2D;
011
012import javax.swing.Icon;
013
014/**
015   An icon that has the shape of a car.
016 */
017public class CarIcon implements Icon
018{
019        /**
020      Constructs a car of a given width.
021      @param aWidth the width of the car
022         */
023        public CarIcon(int aWidth)
024        {
025                width = aWidth;
026        }
027
028        public int getIconWidth()
029        {
030                return width;
031        }
032
033        public int getIconHeight()
034        {
035                return width / 2;
036        }
037
038        public void paintIcon(Component c, Graphics g, int x, int y)
039        {
040                Graphics2D g2 = (Graphics2D) g;
041                Rectangle2D.Double body
042                = new Rectangle2D.Double(x, y + width / 6,
043                                width - 1, width / 6);
044                Ellipse2D.Double frontTire
045                = new Ellipse2D.Double(x + width / 6, y + width / 3,
046                                width / 6, width / 6);
047                Ellipse2D.Double rearTire
048                = new Ellipse2D.Double(x + width * 2 / 3, y + width / 3,
049                                width / 6, width / 6);
050
051                // The bottom of the front windshield
052                Point2D.Double r1
053                = new Point2D.Double(x + width / 6, y + width / 6);
054                // The front of the roof
055                Point2D.Double r2
056                = new Point2D.Double(x + width / 3, y);
057                // The rear of the roof
058                Point2D.Double r3
059                = new Point2D.Double(x + width * 2 / 3, y);
060                // The bottom of the rear windshield
061                Point2D.Double r4
062                = new Point2D.Double(x + width * 5 / 6, y + width / 6);
063
064                Line2D.Double frontWindshield
065                = new Line2D.Double(r1, r2);
066                Line2D.Double roofTop
067                = new Line2D.Double(r2, r3);
068                Line2D.Double rearWindshield
069                = new Line2D.Double(r3, r4);
070
071                g2.fill(frontTire);
072                g2.fill(rearTire);
073                g2.setColor(Color.red);
074                g2.fill(body);
075                g2.draw(frontWindshield);
076                g2.draw(roofTop);
077                g2.draw(rearWindshield);
078        }
079
080        private int width;
081}
082
083