使用定时器实现弹弹球

         今天模拟书上的一个例题做了一个弹弹球,是在画布上的指定位置画多个圆,经过一段的延时后,在附近位置重新画。使球看起来是动,通过JSpinner组件调节延时,来控制弹弹球的移动速度.

        BallsCanvas.java

public class BallsCanvas extends Canvas implements ActionListener,
		FocusListener {

	private Ball balls[]; // 多个球
	private Timer timer;

	private static class Ball {
		int x, y; // 坐标
		Color color; // 颜色
		boolean up, left; // 运动方向

		Ball(int x, int y, Color color) {
			this.x = x;
			this.y = y;
			this.color = color;
			up = left = false;
		}
	}

	public BallsCanvas(Color colors[], int delay) { // 初始化颜色、延时
		this.balls = new Ball[colors.length];
		for (int i = 0, x = 40; i < colors.length; i++, x += 40) {
			balls[i] = new Ball(x, x, colors[i]);
		}
		this.addFocusListener(this);
		timer = new Timer(delay, this); // 创建定时器对象,delay指定延时
		timer.start();

	}

	// 设置延时
	public void setDelay(int delay) {
		timer.setDelay(delay);
	}

	// 在canvas上面作画
	public void paint(Graphics g) {
		for (int i = 0; i < balls.length; i++) {
			g.setColor(balls[i].color); // 设置颜色
			balls[i].x = balls[i].left ? balls[i].x - 10 : balls[i].x + 10;
			if (balls[i].x < 0 || balls[i].x >= this.getWidth()) { // 到水平方向更改方向
				balls[i].left = !balls[i].left;
			}

			balls[i].y = balls[i].up ? balls[i].y - 10 : balls[i].y + 10;
			if (balls[i].y < 0 || balls[i].y >= this.getHeight()) { // 到垂直方向更改方向
				balls[i].up = !balls[i].up;
			}
			g.fillOval(balls[i].x, balls[i].y, 20, 20); // 画指定直径的圆
		}
	}

	// 定时器定时执行事件
	@Override
	public void actionPerformed(ActionEvent e) {
		repaint(); // 重画
	}

	// 获得焦点
	@Override
	public void focusGained(FocusEvent e) {
		timer.stop(); // 定时器停止

	}

	// 失去焦点
	@Override
	public void focusLost(FocusEvent e) {
		timer.restart(); // 定时器重启动

	}
}


        BallsJFrame.java

class BallsJFrame extends JFrame implements ChangeListener {

		private BallsCanvas ball;
		private JSpinner spinner;

		public BallsJFrame() {
			super("弹弹球");
			this.setBounds(300, 200, 480, 360);
			this.setDefaultCloseOperation(EXIT_ON_CLOSE);
			Color colors[] = { Color.red, Color.green, Color.blue,
					Color.magenta, Color.cyan };
			ball = new BallsCanvas(colors, 100);
			this.getContentPane().add(ball);

			JPanel panel = new JPanel();
			this.getContentPane().add(panel, "South");
			panel.add(new JLabel("Delay"));
			spinner = new JSpinner();
			spinner.setValue(100);
			panel.add(spinner);
			spinner.addChangeListener(this);
			this.setVisible(true);
		}

		@Override
		public void stateChanged(ChangeEvent e) {
			// 修改JSpinner值时,单击JSpinner的Up或者down按钮时,或者在JSpinner中按Enter键
			ball.setDelay(Integer.parseInt("" + spinner.getValue()));

		}

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

}


         效果如下:

 

posted @ 2012-03-28 10:58  IT专业户  阅读(136)  评论(0编辑  收藏  举报