Home > Java > javaTutorial > How can I create a Java application that displays multiple bouncing balls without them overlapping?

How can I create a Java application that displays multiple bouncing balls without them overlapping?

Patricia Arquette
Release: 2024-12-16 02:35:14
Original
257 people have browsed it

How can I create a Java application that displays multiple bouncing balls without them overlapping?

Java Bouncing Ball

In this example, we'll create a Java application that draws multiple balls on the screen that bounce off the edges of the frame.

Problem

When trying to draw multiple balls, they overwrite each other because they are being added to the same location.

Solution

To resolve this issue, we need to:

  1. Create a List of Balls: We'll use an ArrayList to store the ball objects.
  2. Add Balls to the Content Pane: Instead of adding the ball objects directly to the content pane, we'll add them to the list.
  3. Draw Balls: We'll iterate through the list and draw each ball at its designated location.
  4. Handle Movement: Each ball will have its own thread to handle its movement, ensuring that they don't overwrite each other.

Here's a modified code that implements these changes:

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;
        for (Ball ball : balls) {
            ball.paint(g2);
        }
    }

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

    public void move() {
        for (Ball ball : balls) {
            int newX = ball.x + ball.vx;
            int newY = ball.y + ball.vy;

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

    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);
        ball1.balls.add(ball1);
        ball2.balls.add(ball2);
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
        ball1.start();
        ball2.start();
    }
}
Copy after login

In this updated solution:

  • We create separate Ball objects and add them to a list.
  • We iterate through the list in paintComponent to draw all the balls.
  • Each ball has its own movement thread, preventing overwriting.
  • We also implement a start method to ensure the thread starts after the frame is visible.

By following these steps, we can create a program that successfully draws multiple bouncing balls on the screen.

The above is the detailed content of How can I create a Java application that displays multiple bouncing balls without them overlapping?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template