62,615
社区成员
发帖
与我相关
我的任务
分享
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BallPanel extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame("自由落体模拟");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new BallPanel());
frame.setSize(300, 600);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public BallPanel() {
timer = new Timer( interval, new ActionListener(){
public void actionPerformed(ActionEvent e) {
moveBall();
}
});
timer.start();
}
private void moveBall() {
speed += g * interval / 1000 ;
y += speed;
if( y >= getHeight() - r )
{
y = getHeight() - r;
timer.stop();
}
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(ballColor);
g.fillOval(x, y, r, r);
}
private Color ballColor = Color.red; //小球颜色
private int x = 100, y; //小球初坐标
private int r = 20; //小球半径
private double speed = 0; //速度
private int interval = 50; //间隔时间:50毫秒
private Timer timer; //计时器
static final double g = 9.8; //重力加速度:9.8米/秒,姑且每米算1像素吧,呵呵。
}