Java Bouncing Ball
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.
Analysis and Solution
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:
- A null layout manager should be employed to prevent the layout manager from dictating the layout of the balls.
- The size and location of the ball pane should be controlled, effectively taking over the role of the layout manager.
- The speed and location of the balls should be randomized to reduce the likelihood of identical starting points and movement.
- Only the ball should be updated within the context of the EDT (Event Dispatch Thread).
- The use of X/Y values is redundant and can be eliminated by leveraging the panels themselves.
Code Example
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 getParent().getWidth()) { vx *= -1; } if (y + vy getParent().getHeight()) { vy *= -1; } x += vx; y += vy; // Update the size and location... setSize(getPreferredSize()); setLocation(x, y); } } }
Alternative Approach
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.
Scalability Concerns
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool