Java:用递归画圆

标签 java swing recursion jpanel paintcomponent

所以我试图让我的程序通过递归来画圆圈。每次它进入递归时,圆的半径应该增加 10。它应该是这样的:enter image description here

但是当我运行这段代码在面板上绘制时:

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


}

我明白了:

enter image description here

如果我将圆心设置为常量 250,为什么圆心会发生变化?

最佳答案

因为在 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.

如果 x 和 y 是圆心的坐标,您的代码就可以运行

您应该像这样调整您的代码:

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

关于Java:用递归画圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22178866/

相关文章:

java - 如何使用 NetBeans GUI Builder for Java Swing 添加 GridLayout?

java - 打印使用哪些硬币来赚取给定数量

java - 无效的 SQL 类型 : sqlKind = UNINITIALIZED error is shown

java - eclipse 中 junit 的等宽字体?

java - 终止属性监听器中的线程 (JavaFX 8)

java- 为什么我在使用 gui 创建 ATM 时收到 "class is not abstract and does not override abstract method"?

java - 以圆形路径移动 ImageView

java - BufferedImage 的 getSubimage 性能

python - 快速排序python递归

javascript - 在 Javascript 中评估表达式树