Q2. Write a Multithreading program
in java for bouncing ball. For each bounce, Change the color of ball randomly.
import java.applet.*;
import java.awt.*;
public class BounceBall extends Applet
implements Runnable
{
int counter;
Thread t;
int x,y,z,k;
int max,min;
public void init()
{
counter=0;
x=300;
k=0;
y=400;
max=300;
min=0;
t=new Thread(this);
t.start();
}
public void run()
{
try
{
while(true)
{
repaint();
Thread.sleep(30);
counter++;
}
}
catch(Exception e)
{
}}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(x,y,120,120);
if(min==0)
{
max=max-10;
y=max;
if(max==100)
min=10;
g.setColor(Color.blue);
g.fillOval(x,y,120,120);
}
if(min==10)
{
max=max+10;
y=max;
if(max==300)
min=0;
g.setColor(Color.red);
g.fillOval(x,y,120,120);
}}}
<html>
<head>
<title>Frame</title>
</head>
<body>
<Applet code=BounceBall.class height=600
width=500></Applet>
</body>
</html>