import java.awt.*;
import java.awt.event.*;
/*定义弹子类*/
class Marble extends Thread{
Table table = null;
int x,y,xdir,ydir;
public Marble(Table _table,int _x,int _y,int _xdir,int _ydir){
table = _table;
x=_x;
y=_y;
xdir=_xdir;
ydir=_ydir;
}
public void run(){
while(true){
if((x>(table.getSize().width)-25)||(x<0))
xdir*=-1;
if(y>(table.getSize().width)-25||(y<0))
ydir*=-1;
x+=xdir;
y+=ydir;
try{
sleep(100);
}catch(InterruptedException e){
System.err.println("Thread interrupted");
}
table.repaint();//重绘图形
}
}
public void draw(Graphics g){
g.setColor(Color.black);
g.fillOval(x, y, 30, 30);
g.setColor(Color.white);
g.fillOval(x+5, y+5, 8, 6);
}
}
/*定义台球桌类*/
class Table extends Frame implements ActionListener{
Button start=new Button("开始");
Marble marbles[]=new Marble[5];//建立弹子线程类对象数组
int v=2;//设置速度最小值
public Table(){
super("弹子台球");
setSize(300,300);
setBackground(Color.cyan);
setVisible(true);
setLayout(new FlowLayout());
add(start);
start.addActionListener(this);
validate();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae){
for(int i=0;i<marbles.length;i++){
int xdir=i*(i-i*(int)Math.round(Math.random()))+v;
int ydir=i*(i-i*(int)Math.round(Math.random()))+v;
System.out.println(xdir);
System.out.println(ydir);
int x=(int)(getSize().width*Math.random());
int y=(int)(getSize().height*Math.random());
//上面随产生弹子的速度和初始坐标位置
marbles[i]=new Marble(this,x,y,xdir,ydir);
marbles[i].start();
}
}
public void paint(Graphics g){
for(int i=0;i<marbles.length;i++){
if(marbles[i]!=null)
marbles[i].draw(g);
}
}
}
public class Ex {
public static void main(String[] args){
Table table=new Table();
}
}
此程序只考虑了各个弹子与墙壁碰撞后改变方向,而没有考虑弹子之间的碰撞。各个弹子都是一个独立的线程,而没有编写线程通信方面的程序。下一阶段是做线程通信方面的工作。