001package horstmann.ch04_animation; 002import java.awt.Graphics2D; 003import java.awt.geom.Ellipse2D; 004import java.awt.geom.Line2D; 005import java.awt.geom.Point2D; 006import java.awt.geom.Rectangle2D; 007 008/** 009 A car that can be moved around. 010 */ 011public class CarShape implements MoveableShape 012{ 013 /** 014 Constructs a car item. 015 @param x the left of the bounding rectangle 016 @param y the top of the bounding rectangle 017 @param width the width of the bounding rectangle 018 */ 019 public CarShape(int x, int y, int width) 020 { 021 this.x = x; 022 this.y = y; 023 this.width = width; 024 } 025 026 public void translate(int dx, int dy) 027 { 028 x += dx; 029 y += dy; 030 } 031 032 public void draw(Graphics2D g2) 033 { 034 Rectangle2D.Double body 035 = new Rectangle2D.Double(x, y + width / 6, 036 width - 1, width / 6); 037 Ellipse2D.Double frontTire 038 = new Ellipse2D.Double(x + width / 6, y + width / 3, 039 width / 6, width / 6); 040 Ellipse2D.Double rearTire 041 = new Ellipse2D.Double(x + width * 2 / 3, y + width / 3, 042 width / 6, width / 6); 043 044 // The bottom of the front windshield 045 Point2D.Double r1 046 = new Point2D.Double(x + width / 6, y + width / 6); 047 // The front of the roof 048 Point2D.Double r2 049 = new Point2D.Double(x + width / 3, y); 050 // The rear of the roof 051 Point2D.Double r3 052 = new Point2D.Double(x + width * 2 / 3, y); 053 // The bottom of the rear windshield 054 Point2D.Double r4 055 = new Point2D.Double(x + width * 5 / 6, y + width / 6); 056 Line2D.Double frontWindshield 057 = new Line2D.Double(r1, r2); 058 Line2D.Double roofTop 059 = new Line2D.Double(r2, r3); 060 Line2D.Double rearWindshield 061 = new Line2D.Double(r3, r4); 062 063 g2.draw(body); 064 g2.draw(frontTire); 065 g2.draw(rearTire); 066 g2.draw(frontWindshield); 067 g2.draw(roofTop); 068 g2.draw(rearWindshield); 069 } 070 071 private int x; 072 private int y; 073 private int width; 074}