碰撞的小球
一、小球运动的状态(线程类)
public class BallThread extends Thread {
Graphics g;
int x=100,y=100;
int vx,vy;
public void run() {
//
double a= (Math.random()*100);
vx=(int)a;
vy=(int)b;
while(true){
System.out.println("true");
g.setColor(new Color(238,238,238));
g.fillOval(x, y, 100, 100);
x+=vx;
y+=vy;
if(x>500){
vx=-vx;
}
if(x<0){
vx=(int)a;
}
if(y>500){
vy=-vy;
}
if(y<0){
vy=(int)b;
}
g.setColor(Color.black);
g.fillOval(x, y, 100, 100);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
二、启动线程
public class BtnListener implements ActionListener{
Graphics g;
@Override
public void actionPerformed(ActionEvent e) {
BallThread ball = new BallThread();
ball.g = g;
//启动线程,不能直接调用run方法
ball.start();
}
}