java弹跳小球源代码
时间: 2024-02-28 15:51:20 浏览: 21
当然可以!以下是一个简单的Java弹跳小球的源代码示例:
```java
import javax.swing.*;
import java.awt.*;
public class BouncingBall extends JPanel {
private int x = 0;
private int y = 0;
private int xSpeed = 1;
private int ySpeed = 1;
public void moveBall() {
x += xSpeed;
y += ySpeed;
if (x < 0 || x > getWidth()) {
xSpeed = -xSpeed;
}
if (y < 0 || y > getHeight()) {
ySpeed = -ySpeed;
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(x, y, 50, 50);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bouncing Ball");
BouncingBall ball = new BouncingBall();
frame.add(ball);
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
ball.moveBall();
ball.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这个程序使用了Java的Swing库来创建一个窗口,并在窗口中绘制一个红色的小球。小球会在窗口中弹跳,当小球碰到窗口的边界时会反弹。