Swing Timer 的使用案例

1. [代码][Java]代码     跳至 [1]  [全屏预览]  
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class BouncingBall extends JPanel implements ActionListener {

	private static final int BALL_SIZE = 25, SPEED = 5;
	
	private int xPos, yPos;
	private int xSpeed, ySpeed;
	
	BouncingBall() {
		// determine a random position for the ball
		Random r = new Random();
		xPos = r.nextInt(300);
		yPos = r.nextInt(300);
		// determine speed direction
		xSpeed = SPEED;
		ySpeed = -SPEED;
		// a timer called every 1/10 second
		Timer timer = new Timer(100, this);
		timer.start();
	}
	public void actionPerformed(ActionEvent e) {
		// get screen size
		int width = getWidth();
		int height = getHeight();
		// update positions
		xPos += xSpeed;
		yPos += ySpeed;
		// test if we go out the screen on the X axis
		if(xPos < 0) {
			xPos = 0;
			xSpeed = SPEED;
		}
		else if(xPos > width - BALL_SIZE) {
			xPos = width - BALL_SIZE;
			xSpeed = -SPEED;
		}
		// test if we go out the screen on the Y axis
		if(yPos < 0) {
			yPos = 0;
			ySpeed = SPEED;
		}
		else if(yPos > height - BALL_SIZE) {
			yPos = height - BALL_SIZE;
			ySpeed = -SPEED;
		}
		// ask to redraw the ball
		repaint();
	}
	// called by the Timer
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.fillOval(xPos, yPos, BALL_SIZE, BALL_SIZE);
	}

	public static void main(String[] args) {
		// a JFrame to test the whole thing
		JFrame frame = new JFrame("Bouncing ball");
		frame.setSize(500, 500);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		// add the bouncing panel to the JFrame
		frame.add(new BouncingBall());
		frame.setVisible(true);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值