Post Views: 3
Write a java program in multithreading using applet for moving car.
import java.applet.Applet;
import java.awt.*;
public class MovingCarApplet extends Applet implements Runnable {
int x = 0; // Initial x-coordinate of the car
Thread t;
public void init() {
setBackground(Color.cyan);
setSize(600, 200);
}
public void start() {
t = new Thread(this);
t.start();
}
public void run() {
try {
while (true) {
x += 5; // Move car 5 pixels at a time
if (x > getWidth()) {
x = -100; // Reset to start from left
}
repaint(); // Call paint() to redraw car
Thread.sleep(100); // Delay for smooth animation
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
public void paint(Graphics g) {
// Draw the ground
g.setColor(Color.green);
g.fillRect(0, 150, getWidth(), 50);
// Draw the car body
g.setColor(Color.red);
g.fillRect(x, 120, 100, 30); // Main body
g.fillRect(x + 20, 100, 60, 20); // Top body
// Draw the wheels
g.setColor(Color.black);
g.fillOval(x + 20, 145, 20, 20); // Left wheel
g.fillOval(x + 60, 145, 20, 20); // Right wheel
}
}