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