Java弹跳球

2024-01-09

我正在尝试编写一个Java应用程序,它在屏幕上绘制多个从框架边缘弹起的球。我能成功抽出一个球。然而,当我添加第二个球时,它会覆盖我绘制的初始球。代码是:

import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class Ball extends JPanel implements Runnable {

    List<Ball> balls = new ArrayList<Ball>();   
Color color;
int diameter;
long delay;
private int x;
private int y;
private int vx;
private int vy;

public Ball(String ballcolor, int xvelocity, int yvelocity) {
    if(ballcolor == "red") {
        color = Color.red;
    }
    else if(ballcolor == "blue") {
        color = Color.blue;
    }
    else if(ballcolor == "black") {
        color = Color.black;
    }
    else if(ballcolor == "cyan") {
        color = Color.cyan;
    }
    else if(ballcolor == "darkGray") {
        color = Color.darkGray;
    }
    else if(ballcolor == "gray") {
        color = Color.gray;
    }
    else if(ballcolor == "green") {
        color = Color.green;
    }
    else if(ballcolor == "yellow") {
        color = Color.yellow;
    }
    else if(ballcolor == "lightGray") {
        color = Color.lightGray;
    }
    else if(ballcolor == "magenta") {
        color = Color.magenta;
    }
    else if(ballcolor == "orange") {
        color = Color.orange;
    }
    else if(ballcolor == "pink") {
        color = Color.pink;
    }
    else if(ballcolor == "white") {     
        color = Color.white;
    }
    diameter = 30;
    delay = 40;
    x = 1;
    y = 1;
    vx = xvelocity;
    vy = yvelocity;
}

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setColor(color);
    g.fillOval(x,y,30,30); //adds color to circle
    g.setColor(Color.black);
    g2.drawOval(x,y,30,30); //draws circle
}

public void run() {
    while(isVisible()) {
        try {
            Thread.sleep(delay);
        } catch(InterruptedException e) {
            System.out.println("interrupted");
        }
        move();
        repaint();
    }
}

public void move() {
    if(x + vx < 0 || x + diameter + vx > getWidth()) {
        vx *= -1;
    }
    if(y + vy < 0 || y + diameter + vy > getHeight()) {
        vy *= -1;
    }
    x += vx;
    y += vy;
}

private void start() {
    while(!isVisible()) {
        try {
            Thread.sleep(25);
        } catch(InterruptedException e) {
            System.exit(1);
        }
    }
    Thread thread = new Thread(this);
    thread.setPriority(Thread.NORM_PRIORITY);
    thread.start();
}

public static void main(String[] args) {
    Ball ball1 = new Ball("red",3,2);
    Ball ball2 = new Ball("blue",6,2);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(ball1);
    f.getContentPane().add(ball2);
    f.setSize(400,400);
    f.setLocation(200,200);
    f.setVisible(true);
    new Thread(ball1).start();
    new Thread(ball2).start();
}
}

我想创建一个球列表,然后循环绘制每个球,但我仍然无法将这两个球添加到内容窗格中。

谢谢你的帮助。


按照你目前的做法...

  • 我看到的主要问题是你将两个不透明的组件放在彼此的顶部......实际上你可能会发现你正在绕过其中一个组件......
  • 你应该使用null布局管理器,否则它将接管并按照它认为合适的方式布局您的球。
  • 您需要确保控制球窗格的大小和位置。这意味着您已经接管了布局管理器的角色......
  • 您需要随机化球的速度和位置,以减少它们在同一位置开始并在同一位置移动的机会......
  • 仅更新Ball在 EDT 的范围内。
  • 您实际上并不需要 X/Y 值,您可以使用面板。

.

public class AnimatedBalls {

    public static void main(String[] args) {
        new AnimatedBalls();
    }

    public AnimatedBalls() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new Balls());
                frame.setSize(400, 400);
                frame.setVisible(true);
            }
        });
    }

    public class Balls extends JPanel {

        public Balls() {
            setLayout(null);
            // Randomize the speed and direction...
            add(new Ball("red", 10 - (int) Math.round((Math.random() * 20)), 10 - (int) Math.round((Math.random() * 20))));
            add(new Ball("blue", 10 - (int) Math.round((Math.random() * 20)), 10 - (int) Math.round((Math.random() * 20))));
        }
    }

    public class Ball extends JPanel implements Runnable {

        Color color;
        int diameter;
        long delay;
        private int vx;
        private int vy;

        public Ball(String ballcolor, int xvelocity, int yvelocity) {
            if (ballcolor == "red") {
                color = Color.red;
            } else if (ballcolor == "blue") {
                color = Color.blue;
            } else if (ballcolor == "black") {
                color = Color.black;
            } else if (ballcolor == "cyan") {
                color = Color.cyan;
            } else if (ballcolor == "darkGray") {
                color = Color.darkGray;
            } else if (ballcolor == "gray") {
                color = Color.gray;
            } else if (ballcolor == "green") {
                color = Color.green;
            } else if (ballcolor == "yellow") {
                color = Color.yellow;
            } else if (ballcolor == "lightGray") {
                color = Color.lightGray;
            } else if (ballcolor == "magenta") {
                color = Color.magenta;
            } else if (ballcolor == "orange") {
                color = Color.orange;
            } else if (ballcolor == "pink") {
                color = Color.pink;
            } else if (ballcolor == "white") {
                color = Color.white;
            }
            diameter = 30;
            delay = 100;

            vx = xvelocity;
            vy = yvelocity;

            new Thread(this).start();

        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;

            int x = getX();
            int y = getY();

            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setColor(color);
            g.fillOval(0, 0, 30, 30); //adds color to circle
            g.setColor(Color.black);
            g2.drawOval(0, 0, 30, 30); //draws circle
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(30, 30);
        }

        public void run() {

            try {
                // Randamize the location...
                SwingUtilities.invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        int x = (int) (Math.round(Math.random() * getParent().getWidth()));
                        int y = (int) (Math.round(Math.random() * getParent().getHeight()));

                        setLocation(x, y);
                    }
                });
            } catch (InterruptedException exp) {
                exp.printStackTrace();
            } catch (InvocationTargetException exp) {
                exp.printStackTrace();
            }

            while (isVisible()) {
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                    System.out.println("interrupted");
                }

                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            move();
                            repaint();
                        }
                    });
                } catch (InterruptedException exp) {
                    exp.printStackTrace();
                } catch (InvocationTargetException exp) {
                    exp.printStackTrace();
                }
            }
        }

        public void move() {

            int x = getX();
            int y = getY();

            if (x + vx < 0 || x + diameter + vx > getParent().getWidth()) {
                vx *= -1;
            }
            if (y + vy < 0 || y + diameter + vy > getParent().getHeight()) {
                vy *= -1;
            }
            x += vx;
            y += vy;

            // Update the size and location...
            setSize(getPreferredSize());
            setLocation(x, y);

        }
    }
}

这种方法的“主要”问题是每个Ball有它自己的Thread。当您增加球的数量时,这将很快消耗您的系统资源......

不同的方法

正如 Hovercraft 所开始的那样,您最好创建一个供球居住的容器,其中的球不是组件,而是球的“虚拟”概念,包含足够的信息以使它们能够从墙壁上反弹。 ..

public class SimpleBalls {

    public static void main(String[] args) {
        new SimpleBalls();
    }

    public SimpleBalls() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Spot");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                Balls balls = new Balls();
                frame.add(balls);
                frame.setSize(400, 400);
                frame.setVisible(true);

                new Thread(new BounceEngine(balls)).start();

            }
        });
    }

    public static int random(int maxRange) {
        return (int) Math.round((Math.random() * maxRange));
    }

    public class Balls extends JPanel {

        private List<Ball> ballsUp;

        public Balls() {
            ballsUp = new ArrayList<Ball>(25);

            for (int index = 0; index < 10 + random(90); index++) {
                ballsUp.add(new Ball(new Color(random(255), random(255), random(255))));
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            for (Ball ball : ballsUp) {
                ball.paint(g2d);
            }
            g2d.dispose();
        }

        public List<Ball> getBalls() {
            return ballsUp;
        }
    }

    public class BounceEngine implements Runnable {

        private Balls parent;

        public BounceEngine(Balls parent) {
            this.parent = parent;
        }

        @Override
        public void run() {

            int width = getParent().getWidth();
            int height = getParent().getHeight();

            // Randomize the starting position...
            for (Ball ball : getParent().getBalls()) {
                int x = random(width);
                int y = random(height);

                Dimension size = ball.getSize();

                if (x + size.width > width) {
                    x = width - size.width;
                }
                if (y + size.height > height) {
                    y = height - size.height;
                }

                ball.setLocation(new Point(x, y));

            }

            while (getParent().isVisible()) {

                // Repaint the balls pen...
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        getParent().repaint();
                    }
                });

                // This is a little dangrous, as it's possible
                // for a repaint to occur while we're updating...
                for (Ball ball : getParent().getBalls()) {
                    move(ball);
                }

                // Some small delay...
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                }

            }

        }

        public Balls getParent() {
            return parent;
        }

        public void move(Ball ball) {

            Point p = ball.getLocation();
            Point speed = ball.getSpeed();
            Dimension size = ball.getSize();

            int vx = speed.x;
            int vy = speed.y;

            int x = p.x;
            int y = p.y;

            if (x + vx < 0 || x + size.width + vx > getParent().getWidth()) {
                vx *= -1;
            }
            if (y + vy < 0 || y + size.height + vy > getParent().getHeight()) {
                vy *= -1;
            }
            x += vx;
            y += vy;

            ball.setSpeed(new Point(vx, vy));
            ball.setLocation(new Point(x, y));

        }
    }

    public class Ball {

        private Color color;
        private Point location;
        private Dimension size;
        private Point speed;

        public Ball(Color color) {

            setColor(color);

            speed = new Point(10 - random(20), 10 - random(20));
            size = new Dimension(30, 30);

        }

        public Dimension getSize() {
            return size;
        }

        public void setColor(Color color) {
            this.color = color;
        }

        public void setLocation(Point location) {
            this.location = location;
        }

        public Color getColor() {
            return color;
        }

        public Point getLocation() {
            return location;
        }

        public Point getSpeed() {
            return speed;
        }

        public void setSpeed(Point speed) {
            this.speed = speed;
        }

        protected void paint(Graphics2D g2d) {

            Point p = getLocation();
            if (p != null) {
                g2d.setColor(getColor());
                Dimension size = getSize();
                g2d.fillOval(p.x, p.y, size.width, size.height);
            }

        }
    }
}

因为这是由单个线程驱动的,所以它的可扩展性更高。

您还可以查看图像未加载 https://stackoverflow.com/questions/12642852/the-images-are-not-loading/12648265#12648265这是一个类似的问题;)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java弹跳球 的相关文章

随机推荐

  • 如何将 dapper 与 ASP.Net core Identity 结合使用?

    我有一个数据库 我尝试使用 dapper 和 Core Identity 来查询数据库 但我现在陷入困境 我正在使用 IdentityUser 界面中的用户 public class User IdentityUser 使用 dapper
  • 使用 SemanticResultKey 时出现 TargetInitationException

    我想建立我的语法来接受多个数字 当我重复数字 例如说 二十一 时 它有一个错误 所以我不断减少代码来找出问题所在 我为语法生成器编写了以下代码 string numberString one Choices numberChoices ne
  • Orchard 根据过滤的下拉选择创建投影或搜索

    我认为 我有一个简单的功能 我试图将其添加到我的 Orchard 1 6 站点 但我找不到任何有关如何执行此操作的教程或说明 我有一个名为 Office 的自定义类型 每个办公室都有一个名为 State 的自定义字段 指示办公室所在的州 实
  • 当块后代时关注 ListView 中的 EditText (Android)

    我有一个定制的ListView 每行都有一个EditText Buttons TextView 为了使 ListView 项目可点击 我保留了android descendantFocusability blocksDescendants
  • 如果字典键不可用,则返回默认值

    我需要一种方法来获取字典值 如果其键存在 或者简单地返回None 如果没有 然而 Python 提出了一个KeyError如果您搜索不存在的键 则会出现异常 我知道我可以检查密钥 但我正在寻找更明确的内容 有没有办法直接返回None如果密钥
  • 如何在 OSX 上从命令行打开 Visual Studio Code?

    The docs https code visualstudio com docs codebasics launching vscode提到一个名为的可执行文件code 但我不确定在哪里可以找到它 以便我可以将其放在我的路径上 我从 VS
  • div 边框半径问题(在 Firefox 和 Opera 上)

    正如你所看到的 有两张图片 首先 在 chrome 上 右侧有 Be en 和 Yorumlar 按钮 边框看起来非常好 但第二张照片显示 firefox和opera有边框半径的问题 我尝试做边框宽度 薄 边框 1px实心等 但它看起来一样
  • EC.element_to_be_clickable 和 EC.presence_of_element_ located 之间单击()元素的区别

    我在间歇性单击某个元素时遇到 TimeoutExceptions 我尝试过显式等待和 time sleep 它工作了一段时间 我一次又一次地遇到例外 我想了解这是否是由预期条件引起的 WebDriverWait self driver 40
  • 简单饼图:错误百分比未居中?

    我有一个 symfony 项目 我使用 bootstrap 作为样式 并且我想使用 Easy Pie Chart 作为仪表板页面 所以 在 base html twig 中 block stylesheets endblock block
  • 将任意 GUID 编码为可读 ASCII (33-127) 的最有效方法是什么?

    GUID 的标准字符串表示形式大约需要 36 个字符 这非常好 但也非常浪费 我想知道如何使用 33 127 范围内的所有 ASCII 字符以最短的方式对其进行编码 简单的实现会产生 22 个字符 只是因为128 bits 6 bits产量
  • 来自旋转 JSON 的 D3 多系列折线图

    这里有一个很好的多系列折线图示例http bl ocks org mbostock 3884955 http bl ocks org mbostock 3884955如果 tsv 数据被布置出来 我确信它会看起来像这样 date 20111
  • .NET 进程可以分配的最大内存

    垃圾收集器可以为 NET 进程分配的最大内存是多少 当我编译到 x64 时 Process GetCurrentProcess MaxWorkingSet 返回大约 1 4GB 但是当我编译到 AnyCPU x64 时 返回相同的数字 对于
  • 无法通过 shell 在 CentOS 7 上安装 phpMyAdmin

    yum y install phpmyadmin 出现错误 Error Package phpMyAdmin 4 4 15 10 2 el7 noarch epel Requires php zip Available php common
  • 是否可以在 WPF ItemsControl 中模拟边框折叠(ala CSS)?

    我正在 WPF 中设置项目的样式ListBox 并希望在每个项目周围放置边框 和BorderThickness设置为 1 例如 相邻项目之间的上下边框都会被绘制 因此看起来比侧边框 更厚 如下所示 生成这些的项目模板ListBoxItems
  • ZeroMQ:重新绑定套接字时地址使用错误

    将 ZeroMQ 套接字绑定到端点并关闭套接字后 将另一个套接字绑定到同一端点需要多次尝试 之前的调用zmq bind直到成功失败并出现错误 地址正在使用 EADDRINUSE 下面的代码演示了这个问题 include
  • 是否有一个好的数据结构可以执行查找、并集和解并操作?

    我正在寻找一种可以相当有效地支持并集 查找和解并的数据结构 一切至少 O log n 或更好 因为标准的不相交集结构不支持解并 作为背景 我正在用 MCTS 编写 Go AI http en wikipedia org wiki Monte
  • SSL 和 SocketChannel

    理想情况下 我只需要一个简单的SSLSocketChannel 我已经有一个可以通过普通方式读取和写入消息的组件SocketChannel 但对于其中一些连接 我必须通过网络使用 SSL 然而 这些连接上的操作是相同的 有谁知道免费的SSL
  • 如何在VBA中清空数组?

    我正在开发一个与 COM 服务器交换对象的 Excel VBA 插件 如下所示 get an array of objects Dim Ents As ISomething ComObject GetEntities Ents send a
  • log4j 记录两次

    我正在使用 log4j 来记录错误和其他系统信息 但来自在信息级别记录两次的信息 public static void main final String args throws Exception LOGGER info program
  • Java弹跳球

    我正在尝试编写一个Java应用程序 它在屏幕上绘制多个从框架边缘弹起的球 我能成功抽出一个球 然而 当我添加第二个球时 它会覆盖我绘制的初始球 代码是 import java awt import javax swing import ja