gpt4 book ai didi

java - 使用java的递归方法绘制正方形

转载 作者:行者123 更新时间:2023-12-01 12:29:08 25 4
gpt4 key购买 nike

我正在尝试编写一个小程序,它绘制一个主正方形,然后使用递归方法在主正方形的角上绘制较小的正方形。我真的很困惑如何解决这个问题。我已经绘制了正方形,其他正方形在其角上,但我需要递归地执行此过程,这就是我迷失的地方。我需要设置最小边长,以便递归方法知道何时停止。这是我的代码。

 import javax.swing.JApplet;

import java.awt.*;
public class LabC extends JApplet
{
public void paint(Graphics g)
{
g.drawRect(50, 100, 100, 100);
g.drawRect(25, 75, 50, 50);
g.drawRect(125, 75, 50, 50);
g.drawRect(125, 175, 50, 50);
g.drawRect(25, 175, 50, 50);


}
}

最佳答案

我认为这或多或少是您想要的

    public static class LabC extends JLabel {

public void paintRecursiveWraper(Graphics g, int minW, int minH, int x, int y, int w, int h) {
g.drawRect(x, y, w, h);
paintRecusive(g, minW, minH, x, y, w, h);
}

public void paintRecusive(Graphics g, int minW, int minH, int x, int y, int w, int h) {
if (h <= minH || w <= minW) {
return;
}

int newW, newH;
int newX, newY;
newW = (int) (w * scaleFactor);
newH = (int) (h * scaleFactor);

// Bot Left Square
newX = x;
newY = y;
g.drawRect(newX, newY, newW, newH);
paintRecusive(g, minW, minH, newX, newY, newW, newH);
// Bot Right Square
newX = (int) (x + w * (1 - scaleFactor));
newY = y;
g.drawRect(newX, newY, newW, newH);
paintRecusive(g, minW, minH, newX, newY, newW, newH);
// Top Left Square
newX = x;
newY = (int) (y + h * (1 - scaleFactor));
g.drawRect(newX, newY, newW, newH);
paintRecusive(g, minW, minH, newX, newY, newW, newH);
// Top Right Square
newX = (int) (x + w * (1 - scaleFactor));
newY = (int) (y + h * (1 - scaleFactor));
g.drawRect(newX, newY, newW, newH);
paintRecusive(g, minW, minH, newX, newY, newW, newH);
}

public void paint(Graphics g) {
paintRecursiveWraper(g, 10, 10, 0, 0, 1000, 1000);

}
}

scaleFactor 必须介于 0 和 1 之间

已编辑*

关于java - 使用java的递归方法绘制正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26092404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com