代码改变世界

模拟弹子台球--java多线程应用

2011-09-16 15:39  Rollen Holt  阅读(1293)  评论(0编辑  收藏  举报

运行效果:

代码如下:

Marbles.java

package MarblesThread;

import java.awt.Color;
import java.awt.Graphics;

public class Marbles implements Runnable{
	public Marbles(){

	}

	public Marbles(int startx, int starty, int xdir, int ydir, Table table){
		this.table = table;
		this.startX = startx;
		this.startY = starty;
		this.xDir = xdir;
		this.yDir = ydir;
	}

	@Override
	public void run(){
		while(true){
			if((startX > table.getSize().width - 25) || (startX < 0)){
				xDir *= -1;
			}
			if((startY > table.getSize().width - 25) || (startY < 0)){
				yDir *= -1;
			}
			startX += xDir;
			startY += yDir;
			try{
				Thread.sleep(1000);
			}catch(Exception e){
				e.printStackTrace();
			}
			table.repaint();
		}

	}

	public void draw(Graphics g){
		g.setColor(Color.black);
		g.fillOval(startX, startY, 30, 30);
		g.setColor(Color.white);
		g.fillOval(startX + 5, startY + 5, 8, 6);
	}

	Table table = null;
	int startX, startY;
	int xDir, yDir;
}

Table.java

package MarblesThread;

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Table extends JFrame implements ActionListener{
	public Table(){
		panel.add(startButton);
		startButton.addActionListener(this);
		setContentPane(panel);

		setSize(400, 500);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		addWindowListener(new WindowAdapter(){
			@Override
			public void windowClosing(WindowEvent e){
				System.exit(0);
			}
		});
	}

	public static void main(String[] args){
		new Table();
	}

	private final JButton startButton = new JButton("开始");
	JPanel panel = new JPanel();
	Marbles[] marbles = new Marbles[10];
	private final int speedMin = 2;

	@Override
	public void actionPerformed(ActionEvent e){
		for(int i = 0; i < marbles.length; i++){
			int xDir = (int) (Math.random() * 10 + speedMin);
			int yDir = (int) (Math.random() * 10 + speedMin);
			int startX = (int) (Math.random() * getSize().width);
			int startY = (int) (Math.random() * getSize().height);
			marbles[i] = new Marbles(startX, startY, xDir, yDir, this);
			new Thread(marbles[i]).start();
		}
	}

	@Override
	public void paint(Graphics g){
		super.paint(g);
		for(int i = 0; i < marbles.length; i++){
			if(marbles[i] != null){
				marbles[i].draw(g);
			}
		}
	}
}