模拟弹子台球--java多线程应用
2011-09-16 15:39 Rollen Holt 阅读(1288) 评论(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); } } } }
==============================================================================
本博客已经废弃,不在维护。新博客地址:http://wenchao.ren
我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他
们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其
实我是一个程序员
==============================================================================
![](http://service.t.sina.com.cn/widget/qmd/1882500857/8c17d4b5/1.png)