小球来回弹
时间: 2023-09-10 19:15:34 浏览: 45
要实现小球来回弹的效果,可以在 Ball 类中添加一个速度向量,用它来表示小球的移动方向和速度。当小球碰到窗口的边界时,它的速度方向需要被反转,即横向速度取反或纵向速度取反。
以下是一个简单的示例代码,可以让小球在窗口中来回弹动:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class BouncingBall extends JPanel implements ActionListener {
private static final int WIDTH = 640;
private static final int HEIGHT = 480;
private static final int DELAY = 10;
private int x = 0;
private int y = 0;
private int vx = 3;
private int vy = 2;
private int radius = 20;
public BouncingBall() {
Timer timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
x += vx;
y += vy;
if (x < radius || x > WIDTH - radius) {
vx = -vx;
}
if (y < radius || y > HEIGHT - radius) {
vy = -vy;
}
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.RED);
g2d.fill(new Ellipse2D.Double(x - radius, y - radius, radius * 2, radius * 2));
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bouncing Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.add(new BouncingBall());
frame.setVisible(true);
}
}
```
在上述代码中,vx 和 vy 表示小球的横向和纵向速度,radius 表示小球的半径。在 actionPerformed() 方法中,每次更新小球的位置,如果小球碰到窗口的边界,则反转对应的速度分量。在 paintComponent() 方法中,使用 Graphics2D 绘制小球的图形。
你可以在该示例代码的基础上进行修改和扩展,实现更加丰富的小球运动效果。