import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Polygon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
public class RacingCar extends JFrame {
private static boolean stopTheRace = false;
public static void stopRace(){
stopTheRace = true;
}
public static void startRace(){
stopTheRace = false;
}
public static boolean isStopTheRace(){
return stopTheRace;
}
public RacingCar() {
int x = (int)(Math.random() * 3) + 2;
setLayout(new GridLayout(x, 1, 5,5));
for (int i = 0; i < x; i++){
add(new CarImage(i));
}
}
public static void main(String[] args) {
JFrame frame = new RacingCar();
frame.setTitle("Racing Car");
frame.setSize(1200, 350);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class CarImage extends JPanel {
protected int x = 0;
protected int y = 350;
protected int z = 1200;
protected int c = 0;
protected int carId;
protected int laps = 0;
public CarImage(int id) {
int j = (int)(Math.random() * 70) + 2;
this.carId = id;
final Timer timer1 = new Timer(j, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
x += 10;
c ++;
String CarLane = (carId + 1)+"";
if (laps == 3){
RacingCar.stopRace();
JOptionPane.showMessageDialog(null, "Winner in Lane "
+ CarLane + " ", "Winner winner chicken dinner",
JOptionPane.INFORMATION_MESSAGE);
}
if (RacingCar.isStopTheRace()){
((Timer)e.getSource()).stop();
}
repaint();
}
});
timer1.start();
}
@Override
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 < z - 50) {
g.setColor(Color.BLACK);
g.fillOval(x + 10, y - 11, 10, 10);
g.fillOval(x + 30, y - 11, 10, 10);
g.setColor(Color.BLUE);
g.fillRect(x, y - 21, 50, 10);
g.setColor(Color.GRAY);
g.fillPolygon(polygon);
g.setColor(Color.RED);
}
else {
x = 0;
}
}
}
}