任务描述:实现了动态弹球的功能,对于有弹球功能的SE游戏奠定了基础。

package 运用线程技术的小球;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;//不清楚这个有什么用
import java.util.*;
import javax.swing.*; public class Bounces { public static void main(String[] args) {
// TODO Auto-generated method stub JFrame j = new BounceFrame(); j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); j.setVisible(true); } } class BallRunnable implements Runnable//线程是Thread(Runnable target) 要使用线程 你必须要实现Runnable接口 { private Ball ball; private Component component ; private static final int step = 300000; private static final int delay = 1; public BallRunnable(Ball aball,Component acomponent)
{
ball = aball; component = acomponent; } public void run() { try{ for(int i = 0 ; i <= step ; i++) {
ball.move(component.getBounds()); component.repaint();//面板不断刷新 Thread.sleep(delay); }
}catch(InterruptedException e){} }
} class Ball
{//实现一个小球类 这个小球包含的方法 包括move() private double x = 0; private double y = 0 ; private double dx = 1; private double dy = 1; private static final int XSIZE =15; private static final int YSIZE =15; public void move(Rectangle2D bounds) { x = x + dx; y = y + dy; if(x < bounds.getMinX()) {
x = bounds.getMinX(); dx = -dx; } if(x+XSIZE>=bounds.getMaxX())
{
x = bounds.getMaxX()-XSIZE; dx = - dx; } if(y < bounds.getMinY()) {
y = bounds.getMinY(); dy = -dy; } if(y+YSIZE>=bounds.getMaxY())
{
y = bounds.getMaxY()-YSIZE; dy = - dy; } }//关于小球如何移动 public Ellipse2D getShape() {
return new Ellipse2D.Double(x,y,XSIZE,YSIZE);
}//返回此时的小球的绘画位置
} class BallPanel extends JPanel
{
private ArrayList<Ball> balls = new ArrayList<Ball>(); //定义了一个集合 这个集合是Ball类型的存储 这个知识点很关键 管存储的作用 public void add(Ball b) {
balls.add(b);//将Ball的对象加载进去 }//这就是重写JPanel中的add方法 实现集合加入要更新的小球的重要一步 public void paint(Graphics g)
{ super.paintComponent(g); Graphics2D g2 = (Graphics2D) g;//转换成2D的绘图模式了 for(Ball b :balls) { g2.fill(b.getShape());//这时的g2重新绘制小球的全部信息 fill是 专门绘制图形的方法
} } } class BounceFrame extends JFrame
{ private BallPanel panel; public BounceFrame() { setTitle("小球"); panel = new BallPanel(); panel.setBackground(Color.BLUE); add(panel,BorderLayout.CENTER); JPanel buttonPane = new JPanel(); setBounds(200,200,700,500); addButton(buttonPane,"start",new ActionListener(){ public void actionPerformed(ActionEvent event) { addBall();
}
}); addButton(buttonPane,"Close",new ActionListener(){ public void actionPerformed(ActionEvent event)
{ System.exit(0);
}
}); add(buttonPane,BorderLayout.SOUTH);
} public void addButton(Container c,String title,ActionListener listener)
{
JButton b = new JButton(title); c.add(b); b.addActionListener(listener); }//这个算是变形吧 学习思想 public void addBall()
{ Ball ball = new Ball(); panel.add(ball); Runnable r = new BallRunnable(ball,panel); Thread t = new Thread(r);//Thread(Runnable target) t.start();//启动线程 实质上是启动的run()方法
}
}

动态弹球的实现 加入了多线程技术--javaSE游戏准备工作-LMLPHP

05-08 15:03