这个程序运行起来就是一个窗口,点击开始就出现一个球,开始跳动,然而只能添加一个球,一共就两个球,这个时候只有一个球可以移动。
代码如下:
Bounce.java: 这里是主程序
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//本程序演示 一个球弹跳的动画
public class Bounce {
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame =new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
//里面有球和 按钮的 frame
class BounceFrame extends JFrame
{
//构造函数
public BounceFrame()
{
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
setTitle("Bounce");
comp= new BallComponent();
add(comp,BorderLayout.CENTER);
JPanel buttonPanel=new JPanel();
addButton(buttonPanel,"Start",new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
addBall();
}
}
);
addButton(buttonPanel,"Close",new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);//Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
// This method calls the exit method in class Runtime. This method never returns normally.
}
}
);
add(buttonPanel,BorderLayout.SOUTH);
}
// 添加button 到容器
public void addButton(Container c,String title,ActionListener listener)
{
JButton button =new JButton(title);
c.add(button);
button.addActionListener(listener);
}
//添加一个 跳动的球到panel,并且让他跳动1000次
public void addBall()
{
try
{
Ball ball=new Ball();
comp.add(ball);
for(int i=1;i<=STEPS;i++)
{
ball.move(comp.getBounds());
comp.paint(comp.getGraphics());
Thread.sleep(DELAY);
}
}
catch (InterruptedException e)
{
}
}
private BallComponent comp;
public static final int DEFAULT_WIDTH=450;
public static final int DEFAULT_HEIGHT=350;
public static final int STEPS=1000;
public static final int DELAY=3;
}
//
Ball.java: 定义了球和 移动方法
import java.awt.geom.*;
//一个可以移动的球,还可以在四边形边缘跳动
public class Ball {
//移动球到下一个位置,碰到 边缘就反向
public void move(Rectangle2D bounds)
{
x+=dx;
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;
}
}
//得到 球的shape 作为它的当前的位置
public Ellipse2D getShape()
{
return new Ellipse2D.Double(x,y,XSIZE,YSIZE);
}
private static final int XSIZE=15;
private static final int YSIZE=15;
private double x=0;
private double y=0;
private double dx=1;
private double dy=1;
}
类:BallComponent.java 负责:绘制球
import java.awt.*;
import java.util.*;
import javax.swing.*;
//本组件负责绘制球
public class BallComponent extends JPanel
{
// 添加一个球到 组件 component
public void add(Ball b)
{
balls.add(b);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);//擦除背景
Graphics2D g2=(Graphics2D) g;
for(Ball b:balls)
{
g2.fill(b.getShape());
}
}
private ArrayList<Ball> balls=new ArrayList<Ball>();
}
运行结果:
点击Start 出现一个球,在运动
再次点击 Start 可以又出现一个球,但是这个时候只有这个新球可以运动。
下面该书会将该例子进行改造,添加多线程支持。