日期:2014-05-20 浏览次数:20716 次
import java.awt.*;
import javax.swing.*;
class Ball extends Canvas
{
private Color color;
private int radius;
private int x;
private int y;
private int xSpeed;
private int ySpeed;
public void setXY(int x,int y){
this.x=x;
this.y=y;
repaint();
}
public void setColor(Color color){
this.color=color;
}
Ball(int radius){
setSize(10,10);
xSpeed=(int)(Math.random()*10)+5;
ySpeed=(int)(Math.random()*10)+5;
this.radius=radius;
x=(int)(Math.random()*100);
y=(int)(Math.random()*100);
color=(int)((Math.random())*10)>5?Color.blue:Color.green;
}
public void paint(Graphics g){
g.setColor(color);
g.fillOval(x,y,radius,radius);
}
public void setSpeed(int x,int y){
xSpeed=x;ySpeed=y;
}
public int xSpeed(){return xSpeed;}
public int ySpeed(){return ySpeed;}
public int X(){return this.x;}
public int Y(){return this.y;}
public int R(){return this.radius;}
public Color color(){return this.color;}
}
class movement extends JFrame implements Runnable
{
Ball []ball=new Ball[2];
Thread []thread=new Thread[2];
movement(){
JPanel p=new JPanel();
thread[1]=new Thread(this);
thread[0]=new Thread(this);
ball[1]=new Ball(10);
ball[0]=new Ball(10);
p.add(ball[0]);
p.add(ball[1]);
this.setBounds(0,0,500,500);
this.add(p);
thread[0].start();
thread[1].start();
}
public void run(){
boolean flag=false;
while(true){
flag=false;
int num=Integer.MAX_VALUE;
Thread temp=Thread.currentThread();
for(int i=0;i<2;i++){
if(temp.equals(thread[i]))
{
flag=true;
num=i;
break;
}
}
if(flag){
if(ball[num].X()<=ball[num].R()||ball[num].X()>=400-ball[num].R())
ball[num].setSpeed(-1*ball[num].xSpeed(),ball[num].ySpeed());
if(ball[num].Y()>=500-4*ball[num].R()||ball[num].Y()<=ball[num].R())
ball[num].setSpeed(ball[num].xSpeed(),-1*ball[num].ySpeed());
ball[num].setXY(ball[num].X()+ball[num].xSpeed(),ball[num].Y()+ball[num].ySpeed());
try{Thread.sleep(50);}catch(Exception e){}
ball[num].repaint();
}
}
}
}
class exam
{
public static void main(String[] args)
{
movement move=new movement();
move.setVisible(true);
move.setDefaultCloseOperation(3);
}
}