📄 ball.java
字号:
import java.awt.event.*;
import javax.swing.Timer;
import java.awt.*;
import javax.swing.*;
public class Ball extends JPanel implements ActionListener {
private int delay = 10;
// Create a timer with delay 1000 ms
protected Timer timer = new Timer(delay, this);
private int x = 0; private int y = 0; // Current ball position
private int radius = 15; // Ball radius
private int dx = 2; // Increment on ball's x-coordinate
private int dy = 2; // Increment on ball's y-coordinate
public Ball() {
timer.start();
}
/** Handle the action event */
public void actionPerformed(ActionEvent e) {
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
// Check boundaries
if (x < radius) dx = Math.abs(dx);
if (x > getWidth() - radius) dx = -Math.abs(dx);
if (y < radius) dy = Math.abs(dy);
if (y > getHeight() - radius) dy = -Math.abs(dy);
// Adjust ball position
x += dx;
y += dy;
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
public void suspend() {
timer.stop(); // Suspend clock
}
public void resume() {
timer.start(); // Resume clock
}
public void setDelay(int delay) {
this.delay = delay;
timer.setDelay(delay);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -