This issue concerns a Java application designed to render multiple balls on an interface that bounce off the borders. The user has successfully implemented the drawing of a single ball but runs into problems when attempting to add a second ball, as it overwrites the first ball.
To address this, a list of balls can be created and cycled through to draw each ball, but the user encounters difficulty in adding both balls to the content pane.
The primary problem is the placement of two opaque components on top of one another, potentially causing one to obscure the other. To resolve this:
An improved code example incorporating these modifications:
public class Balls { public Balls() { 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 TheBalls()); frame.setSize(400, 400); frame.setVisible(true); } }); } public class TheBalls extends JPanel { public TheBalls() { 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); } } }
Alternatively, a container could be created to house the balls, where the balls themselves are not components but exist as virtual concepts with sufficient information to enable bouncing off surfaces.
It's important to note that the provided code snippet utilizes a separate thread for each ball, which can impact system resources when the number of balls increases. To address this scalability issue, a single BounceEngine thread can be used to handle all ball movements.
The above is the detailed content of How to Prevent Overlapping Bouncing Balls in a Java Application?. For more information, please follow other related articles on the PHP Chinese website!