Question
-
- Description of a project: Write an applet that simulates four cars racing as shown in Figure 1. The car moves from left to right. When it hits the right end, it restarts from left and continues the same process. You can use a timer to control animation. Redraw the car with a new base coordinates (x, y), as shown in Figure1(c).
- You can set the speed for each car.
-
- Description of a project: Write an applet that simulates four cars racing as shown in Figure 1. The car moves from left to right. When it hits the right end, it restarts from left and continues the same process. You can use a timer to control animation. Redraw the car with a new base coordinates (x, y), as shown in Figure1(c).
- You can set the speed for each car.
Explanation / Answer
RacingCar.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RacingCar extends JFrame { public RacingCar() { add(new CarImage()); } public static void main(String[] args) { JFrame frame = new RacingCar(); frame.setTitle("Racing Car"); frame.setSize(300, 150); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } class CarImage extends JPanel { protected int x = 0; protected int y = 150; protected int z = 300; protected int c = 0; public CarImage() { Timer timer1 = new Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent e) { x += 10; c ++; repaint(); } }); timer1.start(); } public void paintComponent(Graphics g) { super.paintComponent(g); // x = 0; y = getHeight(); z = getWidth(); g.setColor(Color.WHITE); g.fillRect(0, 0, z, y); Polygon polygon = new Polygon(); polygon.addPoint(x + 10, y - 21); polygon.addPoint(x + 20, y - 31); polygon.addPoint(x + 30, y - 31); polygon.addPoint(x + 40, y - 21); if (x