从单独的方法中使用 java awt drawRect?

Use java awt drawRect from a separate method?

我试图在逐个像素的基础上绘制 Sierpinski 的三角形,它会在 window 大小更改时自行调整大小。我相信我已经完成了大部分项目,但我不太清楚如何从 paintComponent 方法之外的单独递归函数绘制矩形。

public class SierpTriangle extends JPanel 
{
    public final int x = this.getWidth();
    public final int y = this.getHeight();
    public final int side = getsize();

    public int getsize()
    {
        int width = this.getWidth();
        int height = this.getHeight();
        if (width <= height) 
        {
            return width;            
        } 
        else 
        {
            return height;             
        }
    }

    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);
        drawSierpTriangle(this.x, this.y, this.side);
        g.drawRect(x,y,1,1);
    }

    public void drawSierpTriangle(int x, int y, int size) 
    {
        if (size == 1)
        {
            //Draw rectangle? This is where I need help

            g.drawRect(x,y,1,1); //this does not work, passing Graphics g into the method also does not work
        } 
        else 
        {
            drawSierpTriangle(x/2, y, size/2);
            drawSierpTriangle(x,y/2,size/2);
            drawSierpTriangle(x/2,y/2,size/2);
        }   
    }

    public static void main(String[] args)
    {
        new SierpFrame();
    }
}

Graphics 的引用从 paintComponent 传递到 drawSierpTriangle

public void paintComponent(Graphics g) 
{
    super.paintComponent(g);
    drawSierpTriangle(g, this.x, this.y, this.side);
    g.drawRect(x,y,1,1);
}

public void drawSierpTriangle(Graphics g, int x, int y, int size) 
{
    if (size == 1)
    {
        //Draw rectangle? This is where I need help

        g.drawRect(x,y,1,1); //this does not work, passing Graphics g into the method also does not work
    } 
    else 
    {
        drawSierpTriangle(g, x/2, y, size/2);
        drawSierpTriangle(g, x,y/2,size/2);
        drawSierpTriangle(g, x/2,y/2,size/2);
    }   
}

This results in: Exception in thread "AWT-EventQueue-0" java.lang.WhosebugError at the first recursive call of the method. Any input?

public final int side = getsize();

将使side永远0

将其替换为更像...

public int getSide() {
    int width = this.getWidth();
    int height = this.getHeight();
    if (width <= height) {
        return width;
    } else {
        return height;
    }
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    int side = getSide();
    if (side == 0) return;
    drawSierpTriangle(g, this.x, this.y, side);
    g.drawRect(x, y, 1, 1);
}

这将在每次绘制组件时计算 side。如果边是 0

,它也会跳过绘制形状

你也会遇到与 xy 相同的问题,因为它们的状态永远不会改变