import java.awt.*; // Graphics import java.awt.event.*; // for Timer, ActionEvent import javax.swing.*; // JPanel, JFrame public class Ch16_15 { public static void main(String[] args) { JFrame f=new JFrame("racing car"); f.setSize(500,150); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RacePanel rp=new RacePanel(); f.add(rp); f.setVisible(true); } public static class RacePanel extends JPanel implements ActionListener // draw onto the JPanel and use the Timer { private int x,y; // x,y coordinate of the lower left hand corner of the car public RacePanel() { Timer t=new Timer(10,this); // create the Timer, set for 10 millisecond delay x=20; // starting x coordinate of the car y=80; // y coordinate of the bottom of the car, will not change t.start(); // start the Timer to animate the image } public void actionPerformed(ActionEvent e) // called each time the Timer reaches the end of its delay { x++; // move the car horizontally by 1 pixel, increase this to make the car move faster if(x>420) x=20; // if it reaches the right border, start it over on the left repaint(); // now that we've moved the car, call paintComponent to redraw it at its new position } public void paintComponent(Graphics g) { super.paintComponent(g); // blank the screen to start new int[] a={x+10,x+20,x+30,x+40}; // draw the canopy portion of the car as a polygon int[] b={y-20,y-30,y-30,y-20}; g.setColor(Color.black); // set color to black for the tires g.fillOval(x+10,y-10,10,10); // back tire g.fillOval(x+30,y-10,10,10); // front tire g.setColor(Color.gray); // use grey for the body g.fillRect(x,y-20,50,10); // the body of the car g.setColor(Color.green); // use green for the canopy g.fillPolygon(a,b,4); // draw the canopy } } }