// From text by Cay Horstmann: Java Concepts, 2005. //cmc: modified in lecture (except cmc comments), 2/27/09 import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JComponent; import java.awt.Color; //cmc: to color cars /** This component draws two car shapes. */ public class CarComponent extends JComponent { //cmc: cars changed to instance variables private Car car1, car2; public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; if (car1 == null) { //cmc: create cars first call only car1 = new Car(0, 0, Color.RED); //cmc: in color int x = getWidth() - Car.WIDTH; int y = getHeight() - Car.HEIGHT; car2 = new Car(x, y, Color.BLUE); } car1.draw(g2); car2.draw(g2); } //cmc: sets the cars in motion public void animate() { for (int i=0; i<20; i++) { // waste one-half second (500 milliseconds) try{ Thread.sleep(500); } catch (InterruptedException e) {} // move the cars car1.forward(5); car2.backward(10); // special method eventually calls paintComponent again repaint(); } } }