Search code examples
javaswingloopspaintoval

Java creating multiple Balls using paintcomponent


I want to create a method that creates 5 balls on a panel. Can somebody please help me get around this using the paint component method or creating my own draw method. As you can see bellow, i have a paint component method with a for loop that will loop 5 and create a ball in a random location, but unfortunately only one ball is being created.

import java.awt.*;
import java.util.Random;
import javax.swing.*;

public class AllBalls extends JPanel {
    int Number_Ball=5;
    int x,y;
    Graphics g;
    AllBalls(){
        Random r = new Random();
        x=r.nextInt(320);
        y=r.nextInt(550);
    }
public static JFrame frame;
    public static void main(String[] args) {
        AllBalls a= new AllBalls();
        frame= new JFrame("Bouncing Balls");
        frame.setSize(400,600);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(a);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for(int i=0;i<Number_Ball;i++){
            g.fillOval(x, y, 30, 30);
        }
        repaint();
    }

}

Solution

  •     Random r = new Random();
        x=r.nextInt(320);
        y=r.nextInt(550);
    

    You only create one random point, not 5.

    If you want 5 random points then you need to create an ArrayList to store your 5 random points. Something like:

    ArrayList<Point> balls = new ArrayList<Point>(5); // instance variable
    
    AllBalls()
    {
        Random r = new Random();
    
        for (int i = 0; i < 5; i++)
            balls.add( new Point(r.nextInt(320), r.nextInt(550));
    }
    

    Then in the paintComponent() method you need to iterate through all the points:

    for (Point p: balls)
        g.fillOval(p.x, p.y, 30, 30);
    

    Also, get rid of the repaint() statement. Never invoke repaint() in a painting method, this will cause an infinite loop.