Bounce类变成了BounceThread类,其他两个类都是和例子14-1是一样的,上一篇博文里面有代码,这里就不重复了。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//本程序演示 一个球弹跳的动画
public class BounceThread {
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);
}
});
}
}
// A Runnable that animates a bouncing ball
class BallRunnable implements Runnable
{
//构造这个 runable
public BallRunnable(Ball aBall,Component aComponent)
{
ball =aBall;
component=aComponent;
}
public void run()
{
try
{
for(int i=1;i<=STEPS;i++)
{
ball.move(component.getBounds());
component.repaint();
Thread.sleep(DELAY);
}
}
catch(InterruptedException e)
{
}
}
private Ball ball;
private Component component;
public static final int STEPS=1000;
public static final int DELAY=5;
}
//里面有球和 按钮的 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);
}
//添加一个 跳动的球到canvas,并且开始一个thread 来让它bounce
public void addBall()
{
Ball nball=new Ball();
comp.add(nball);
/* for(int i=1;i<=STEPS;i++)
{
ball.move(comp.getBounds());
comp.paint(comp.getGraphics());
Thread.sleep(DELAY);
}
*/
Runnable r=new BallRunnable(nball,comp);
Thread t=new Thread(r);
t.start();
}
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;
}
运行结果
这个时候点击一下Start,就会出现要给小球。