Monday, 6 November 2023

Write a java program using Applet for bouncing ball. Ball should change its color for each bounce.

 

Write a java program using Applet for bouncing ball. Ball should change its color for each bounce.

import java.applet.*;

import java.awt.*;

 

public class BouncingBallApplet extends Applet implements Runnable {

    private int x, y; // Current position of the ball

    private int xSpeed, ySpeed; // Speed of the ball

    private Color[] colors = { Color.RED, Color.GREEN, Color.BLUE, Color.ORANGE, Color.MAGENTA };

    private int colorIndex = 0;

 

    public void init() {

        x = 100;

        y = 100;

        xSpeed = 3;

        ySpeed = 2;

    }

 

    public void start() {

        Thread t = new Thread(this);

        t.start();

    }

 

    public void run() {

        while (true) {

            if (x < 0 || x > getWidth() - 20) {

                xSpeed = -xSpeed; // Reverse direction when hitting the left or right edge

                changeColor();

            }

            if (y < 0 || y > getHeight() - 20) {

                ySpeed = -ySpeed; // Reverse direction when hitting the top or bottom edge

                changeColor();

            }

            x += xSpeed;

            y += ySpeed;

            repaint();

 

            try {

                Thread.sleep(16); // Sleep for a short time to control animation speed

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

 

    private void changeColor() {

        colorIndex = (colorIndex + 1) % colors.length;

        setBackground(colors[colorIndex]);

    }

 

    public void paint(Graphics g) {

        g.setColor(Color.WHITE);

        g.fillRect(0, 0, getWidth(), getHeight());

        g.setColor(colors[colorIndex]);

        g.fillOval(x, y, 20, 20);

    }

}