Search code examples
javaswingrecursionjpanelpaintcomponent

Java: drawing circles with recursion


So I am trying to get my program to draw circles through recursion. Each time it steps into the recursion the radius of the circle should increase by 10. Here is what it should look like:enter image description here

but when i run this code to draw on the panel:

class CirclePanel extends JPanel{
public int radius = 25;
int xPossition = 250;
int yPossition = 250;
    @Override
public void paintComponent(Graphics g){
    super.paintComponents(g);

    g.setColor(Color.BLUE);
    g.drawOval(250, 250, radius, radius);
    radius += 10;

    if (radius + 10 < 250){
    paintComponent(g);
    }
    }


}

i get this:

enter image description here

why does the center point of the circle change if i have it set to a constant 250?


Solution

  • drawOval accepts the top-left position and the width and height, not the centre position and the width and height.

    It should be something like this:

    public void paintComponent(Graphics g) {
        super.paintComponents(g);
    
        g.setColor(Color.BLUE);
        g.drawOval(250 - radius, 250 - radius, radius * 2, radius * 2);
        radius += 10;
    
        if (radius + 10 < 250) {
            paintComponent(g);
        }
    }