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);
}
}
Swing Timer 的使用案例
最新推荐文章于 2021-02-24 11:11:34 发布