小苹果熊 2023-02-10 16:40 采纳率: 66.7%
浏览 34
已结题

java小球运动,和线程有关

这里的小球其实就是下雨时的雨点
题目要求各种颜色的小球像下雨一样降落,速度可以调整

  • 写回答

3条回答 默认 最新

  • CodeBytes 2023-02-10 23:22
    关注

    该回答引用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;
           
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 12月23日
  • 已采纳回答 12月15日
  • 创建了问题 2月10日

悬赏问题

  • ¥18 help me! 希望大家来看看 吉~
  • ¥15 C++显示超限兔子集结
  • ¥15 sql server 2012的下载出错
  • ¥15 图像识别用户软件开发
  • ¥20 类原生rom lineageos
  • ¥15 有没有会做中专,云计算,卷子的,有偿一百块
  • ¥15 HC32串口DMA循环发送数据
  • ¥15 Uni-App实现飞书授权登陆
  • ¥50 Qt应用中如何通过代码打开开发者工具devtools
  • ¥20 mpp硬解码h264转为yuv