这里的小球其实就是下雨时的雨点
题目要求各种颜色的小球像下雨一样降落,速度可以调整
这和线程有什么关系,最后要显示的时候还是UI线程在显示
你写个循环就行了
先定义雨点类,里面要有雨点的颜色、大小、速度、坐标什么的
然后随机雨点add到一个list里,循环根据速度改变坐标,已经掉地上的移走
雨点本身受空气阻力很大,所以匀速运动就行了,不用考虑加速度
该回答引用ChatGPT
首先,您需要定义一个类来表示每个小球,并将其坐标以及速度储存在对象中。然后,您可以创建多个对象来代表不同颜色的小球,并通过每次绘图操作来更新小球的位置。下面是一个简单的实现
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Raindrop extends JPanel {
private static final long serialVersionUID = 1L;
private ArrayList<Ball> balls;
private int width;
private int height;
private int speed;
public Raindrop(int width, int height, int speed) {
this.width = width;
this.height = height;
this.speed = speed;
setPreferredSize(new Dimension(width, height));
balls = new ArrayList<Ball>();
}
public void addBall(Color color, int x, int y, int speed) {
balls.add(new Ball(color, x, y, speed));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Ball ball : balls) {
ball.update();
g.setColor(ball.getColor());
g.fillOval(ball.getX(), ball.getY(), 20, 20);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Raindrop raindrop = new Raindrop(500, 500, 1);
raindrop.addBall(Color.BLUE, 50, 50, 1);
raindrop.addBall(Color.RED, 100, 100, 2);
raindrop.addBall(Color.GREEN, 150, 150, 3);
frame.add(raindrop);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
while (true) {
raindrop.repaint();
try {
Thread.sleep(16);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Ball {
private Color color;
private int x;
private int y;
private int speed;
public Ball(Color color, int x, int y, int speed) {
this.color = color;
this.x = x;
this.y = y;
this.speed = speed;
不知道你这个问题是否已经解决, 如果还没有解决的话: