0% found this document useful (0 votes)
4 views

Java Assignment

java c

Uploaded by

prathviacharya17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Assignment

java c

Uploaded by

prathviacharya17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

CODE :

import java.awt.*;
import java.applet.Applet;
public class BouncingBall extends Applet implements Runnable
{
protected Color color;
protected int radius;
protected int x,y;
protected int dx,dy;
protected Graphics offscreen;
protected Image image;
protected Dimension d;
protected Thread bouncingThread;
protected int delay;
public void init()
{
color=Color.green;
radius=20;
dx=-2;
dy=-4;
delay=100;
d=getSize();
x=d.width*2/3;
y=d.height-radius;
}
public void start()
{
bouncingThread=new Thread(this);
bouncingThread.start();
}
public void stop()
{
bouncingThread=null;
}
public void run()
{
while(Thread.currentThread()==bouncingThread)
{
try
{
Thread.currentThread().sleep(delay);
}catch(InterruptedException e){}
repaint();
}
}
public void update(Graphics g)
{
//create the off screen image buffer
//if it is invoked the first time
if(image==null){
image=createImage(d.width,d.height);
offscreen=image.getGraphics();
}
//draw the background
offscreen.setColor(Color.white);
offscreen.fillRect(0,0,d.width,d.height);
//adjust the position of the ball
//reverse the direction if it touches
//any of the four sides
if(x<radius||x>d.width-radius)
{
dx=-dx;
}
if(y<radius||y>d.height-radius)
{
dy=-dy;
}
x+=dx;
y+=dy;
offscreen.setColor(color);
offscreen.fillOval(x-radius,y-radius,radius*2,radius*2);
g.drawImage(image,0,0,this);
}
public void paint(Graphics g)
{
update(g);
}
}

<applet code="BouncingBall" width=300 height=300> </applet>


OUTPUT :

You might also like