Saturday, March 15, 2014

moving ball in java



import java.applet.*;
import java.awt.*;
import java.util.Random;

public class Bouncing_ball extends Applet implements Runnable {


int x1=100,xrate=1;
int y1=200,yrate=3;
int radius1=20;
Random re;
Thread th;
public void start(){
setBackground(Color.red);
setSize(400,400);
re=new Random();
th=new Thread(this);
th.start();
}
int t=200;
public void run(){
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while( true){
if(x1<=0|| x1>=360){

xrate=-xrate;
if(yrate<0)
yrate=-re.nextInt(4);
else
yrate=re.nextInt(4);
}

if(y1<=0|| y1>=360){

yrate=-yrate;
if(xrate<0)
xrate=-re.nextInt(4);
else
xrate=re.nextInt(4);
}

x1+=xrate;
y1+=yrate;
repaint();
try{

Thread.sleep(20);
}
catch(InterruptedException ex){

}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

}
}
public void paint(Graphics g){
g.setColor(Color.green);
g.fillOval(x1,y1,radius1*2,radius1*2);

}

}

No comments:

Post a Comment

Contributors

Translate