Slip No 29 Q B

Q.Write a java program using Applet for bouncing ball. Ball should change its color for each bounce. [25 M]

Java Applet Program
import java.applet.Applet;
import java.awt.*;

public class BouncingBallApplet extends Applet implements Runnable
{
int x = 50, y = 50;
int dx = 5, dy = 5;
int diameter = 50;
Thread t;
Color ballColor = Color.red;

public void init()
{
setBackground(Color.white);
t = new Thread(this);
t.start();
}

public void paint(Graphics g)
{
g.setColor(ballColor);
g.fillOval(x, y, diameter, diameter);
}

public void run()
{
while(true)
{
x += dx;
y += dy;

// horizontal bounce
if(x <= 0 || x + diameter >= getWidth())
{
dx = -dx;
changeColor();
}

// vertical bounce
if(y <= 0 || y + diameter >= getHeight())
{
dy = -dy;
changeColor();
}

repaint();

try
{
Thread.sleep(30);
}
catch(Exception e){}
}
}

public void changeColor()
{
ballColor = new Color(
(int)(Math.random()*255),
(int)(Math.random()*255),
(int)(Math.random()*255));
}
}
HTML File to Run Applet
<html>
<body>
<applet code="BouncingBallApplet.class" width="400" height="300">
</applet>
</body>
</html>
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top