我正在尝试编写一个绘制主正方形的applet,然后使用递归方法在主正方形的角上绘制较小的正方形。我真的很困惑如何解决这个问题。我已经在其角落上绘制了其他正方形的正方形,但我需要递归地执行此过程,这就是我迷失的地方。我需要设置一个最小边长,以便递归方法知道何时停止。这是我的代码。
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);
}
}
答案 0 :(得分:1)
我认为这或多或少是你在寻找什么
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之间
编辑*