0

I am presently planning to write some code for collision detection. However, I came across a problem. I want to draw multiple spheres on the JFrame window but the following code isn't working... Kindly help me out... This is my code :-

    import javax.swing.*;
    import java.awt.*;
    class Draw extends JPanel
    {
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            for(int i=0;i<20;i++)
                drawing(g,new Sphere());
        }
        public void drawing(Graphics g,Sphere s)
        {
            g.setColor(s.color);
            g.fillOval(s.x,s.y,s.radius*2,s.radius*2);
        }
        public static void main(String args[])
        {
            JFrame jf = new JFrame("Renderer");
            jf.getContentPane().add(new Draw(),BorderLayout.CENTER);
            jf.setBounds(100,100,400,300);
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jf.setVisible(true);
        }
    }
    class Sphere
    {
        int x;
        int y;
        int radius;
        Color color;
        public Sphere()
        {
            this.x = (int)Math.random()*100;
            this.y = (int)Math.random()*100;
            this.radius = (int)Math.random()*20;
            this.color = new Color((int)(Math.random()*255),
    (int)(Math.random()*255),(int)(Math.random()*255));
        }
    }
Souparno Paul
  • 17
  • 1
  • 6

2 Answers2

3

You cast the random value to int so that it is 0 and then multiply it. Your Sphere Constructor should look like

public Sphere() {
        this.x = (int) (Math.random() * 100); // cast the result to int not the random
        this.y = (int) (Math.random() * 100);
        this.radius = (int) (Math.random() * 20);
        this.color = new Color((int) ((Math.random() * 255)), (int) (Math.random() * 255), (int) (Math.random() * 255));
}
thopaw
  • 3,796
  • 2
  • 17
  • 24
1
for(int i=0;i<20;i++)
    drawing(g,new Sphere());

A painting method is for painting only.

You should NOT be creating Sphere objects in the paintComponent() method. You can't control when Swing repaints the panel.

Instead, in the constructor of your Draw class you need to create an ArrayList of Sphere objects and you add the 20 objects to the list.

Then you need to add a paint(...) method to your Sphere class so the Sphere object knows how to paint itself. Something like:

public void paint(Graphics g)
{
    g.setColor( color );
    g.fillOval(x, y, width, height) //
}

Then in the paintComponent(...) method your Draw class you need to iterate through the ArrayList and paint each Sphere:

@Override 
protected void paintComponent(Graphics g)
{
    super.paintComponent(g);

    for (each sphere in the ArrayList)
        sphere.paint(g);
}
camickr
  • 321,443
  • 19
  • 166
  • 288