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?

有帮助吗?

解决方案 2

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);
    }
}

其他提示

Because as specified on the documentation

x - the x coordinate of the upper left corner of the oval to be drawn.

y - the y coordinate of the upper left corner of the oval to be drawn.

width - the width of the oval to be drawn.

height - the height of the oval to be drawn.

Your code would work if x and y were the coordinates of the center of the circle

You should adapt your code like:

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-(radius/2), 250-(radius/2), radius, radius);
      radius += 10;

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

The center of the oval is relative to the starting top left corner of the oval that you supply in the first two parameters. Slowly change those to go upwards and to the left on your frame to have it expand like you want, so if you expand the circle by 10 pixels, minus and starting x and y of the top left corner by 5 pixels.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top