写一下点击按钮可以让小球逐步自由下落的代码,要有图形界面,JAVA语言编写
时间: 2023-03-10 14:08:54 浏览: 65
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class BallMovement {
private JFrame frame;
private JButton button;
private int x = 0;
private int y = 0;
public BallMovement() {
frame = new JFrame("Ball Movement");
button = new JButton("Click to Start");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
x = 0;
y = 0;
moveBall();
}
});
frame.add(button, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void moveBall() {
while(x < 300 && y < 300) {
frame.getContentPane().add(new DrawBall(x, y));
frame.setVisible(true);
x += 10;
y += 10;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class DrawBall extends JPanel {
int ballX = 0;
int ballY = 0;
public DrawBall(int x, int y) {
ballX = x;
ballY = y;
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fillOval(ballX, ballY, 20, 20);
}
}
public static void main(String[] args) {
new BallMovement();
}
}
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![html](https://img-home.csdnimg.cn/images/20210720083451.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)