问题: 将多个球添加到 Java 应用程序会生成初始球被第二个覆盖,导致只有一个可见
要解决此问题并在屏幕上绘制多个弹跳球,请考虑以下方法:
< ;h4>4。使用球的容器类:
public class Balls extends JPanel { private List<Ball> ballsUp; // ... (Constructor and other methods) @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 Ball { private Color color; private Point location; private Dimension size; private Point speed; // ... (Constructor and other methods) 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); } } } public class BounceEngine implements Runnable { private Balls parent; // ... (Constructor and other methods) public void run() { // Randomize ball properties and starting positions for (Ball ball : getParent().getBalls()) { // ... (Randomization logic) } while (getParent().isVisible()) { // Repaint the balls SwingUtilities.invokeLater(new Runnable() { @Override public void run() { getParent().repaint(); } }); // Move each ball for (Ball ball : getParent().getBalls()) { move(ball); } // Delay between updates try { Thread.sleep(100); } catch (InterruptedException ex) { } } } // ... (Remaining code) }
这种使用容器类和单独线程进行球运动的方法可以更好地控制球的行为,并允许更复杂的球动画。
以上是如何在 Java 应用程序中显示多个弹跳球而不互相覆盖?的详细内容。更多信息请关注PHP中文网其他相关文章!