CODE:
import java.awt.Graphics;
import java.util.Random;
import java.awt.Color;import java.util.Random;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
class bounceball extends JPanel
{
private static final int win_w=640;
private static final int win_h=480;
private float rad=100;// radius of the ball
private float x=rad+50;
private float y=rad+20;//center coordinates of the ball
private float sx=4;
private float sy=3; //change in the coordinates(x and y)
private static final int update_rate=30;//refresh of screen per second
// Now constructor
private Random r;
private Color clr=Color.BLUE;
public void set(Color c)
{
clr=c;
}
public Color get()
{
return clr;
}
public bounceball()
{
r=new Random();
setPreferredSize(new Dimension(win_w,win_h));//size of the panel is set to
//the size of the window
Thread ballthread=new Thread(){
public void run(){
while(true)
{
x+=sx;
y+=sy;
//here we handle collision with the window walls
//checking the horizontal collision
if(x-rad<0)
{
sx=-sx;//reverse the direction
x=rad;
set(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
}
else if(x+rad>win_w)
{
sx=-sx;
x=win_w-rad;
set(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
}
//checking the vertical collision
if(y-rad<0)
{
sy=-sy;
y=rad;
set(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
}
else if(y+rad>win_h)
{
sy=-sy;
y=win_h-rad;
set(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
}
repaint();
try
{
Thread.sleep(1000/update_rate);
}
catch(InterruptedException e)
{
JOptionPane.showMessageDialog(null,"Please don't interrupt me while sleeping !","Disturbed",JOptionPane.ERROR_MESSAGE);
}
}
}
};
ballthread.start();//start the thread's execution
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0,0,win_w,win_h);
g.setColor(get());
g.fillOval((int)(x-rad),(int)(y-rad),(int)(2*rad),(int)(2*rad));
g.setColor(Color.WHITE);
String s=String.format("Position:[%3.0f,%3.0f]",x,y);
g.drawString(s,20,40);
}
public static void main(String [] args)
{
JFrame jr=new JFrame("Bouncing ball.");
bounceball ball=new bounceball();
jr.add(ball);
jr.setVisible(true);
jr.setSize(650,500);
jr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jr.pack();
}
}
More on this at techcresendo.com
Read More ->>