Problem: Adding multiple balls to a Java application results in the initial ball being overwritten by the second, leading to only one visible ball.
To resolve this issue and draw multiple bouncing balls on screen, consider the following approaches:
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) }
This approach using a container class and a separate thread for ball movement provides greater control over the balls' behavior and allows for more complex ball animation.
The above is the detailed content of How Can I Display Multiple Bouncing Balls in a Java Application Without Overwriting Each Other?. For more information, please follow other related articles on the PHP Chinese website!