所以我试图让我的程序通过递归来画圆圈。每次它进入递归时,圆的半径应该增加 10。它应该是这样的:
但是当我运行这段代码在面板上绘制时:
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);
}
}
}
我明白了:
如果我将圆心设置为常量 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/