package Test;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class BallPanel extends JLabel implements Runnable {
private int r=10;
private int width=r*2;
private int height=r*2;
private Color ballColor=Color.BLUE;
public BallPanel(){
setPreferredSize(new Dimension(width,height));
new Thread(this).start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(ballColor);
g.fillOval(0,0,width,height);
}
public void run(){
Container parent=getParent();
Point myPoint=getLocation();
while(true){
if(parent==null){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myPoint=getLocation();
parent=getParent();
}else{
break;
}
}
int sx=myPoint.x;
int sy=myPoint.y;
int step=(int)(Math.random()*10)%3+1;
int dx=(Math.random()*100)>50?step:-step;
step=(int)(Math.random()*10)%3+1;
int dy=(Math.random()*100)>50?step:-step;
int stime = (int) (Math.random() * 80 + 10);
while(parent.isVisible()){
int parentWidth=parent.getWidth();
int parentHeight=parent.getHeight();
setLocation(sx,sy);
try {
Thread.sleep(stime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sx=sx+dx*5;
sy=sy+dy*5;
if(sy>parent.getHeight()||sy<0)
dy=-dy;
if(sx>parent.getWidth()||sx<0)
dx=-dx;
}
}
}