Question:
What is wrong in my code ?
Repl link:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JungleRace extends JFrame implements ActionListener {
private Lion lion;
private Tiger tiger;
private JLabel scoreLabel;
public JungleRace() {
super("Jungle Race");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
lion = new Lion(100, 100);
tiger = new Tiger(200, 100);
scoreLabel = new JLabel("Lion: 0, Tiger: 0");
add(lion);
add(tiger);
add(scoreLabel);
Timer timer = new Timer(100, this);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
lion.move();
tiger.move();
if (lion.getX() >= getWidth()) {
scoreLabel.setText("Lion: 1, Tiger: 0");
} else if (tiger.getX() >= getWidth()) {
scoreLabel.setText("Lion: 0, Tiger: 1");
}
}
public static void main(String[] args) {
new JungleRace().setVisible(true);
}
}
class Lion extends JPanel implements Runnable {
private int x;
private int y;
private int speed;
public Lion(int x, int y) {
this.x = x;
this.y = y;
this.speed = 10;
}
@Override
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillOval(x, y, 50, 50);
}
@Override
public void run() {
while (true) {
x += speed;
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Tiger extends JPanel implements Runnable {
private int x;
private int y;
private int speed;
public Tiger(int x, int y) {
this.x = x;
this.y = y;
this.speed = 15;
}
@Override
public void paint(Graphics g) {
g.setColor(Color.YELLOW);
g.fillOval(x, y, 50, 50);
}
@Override
public void run() {
while (true) {
x += speed;
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}