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

盾牌

我试图在一个像素一个像素的基础上绘制谢尔宾斯基三角形,它会在窗口大小改变时调整自身大小。我相信我已经完成了大部分项目,但我不太知道如何从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();
    }
}
疯狂程序员

传递GraphicsfrompaintComponentdrawSierpTriangle

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

这会导致: 在第一次递归调用该方法时,线程“AWT-EventQueue-0”中的异常 java.lang.StackOverflowError。任何输入?

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每次绘制组件时进行评估如果 side 是,它也将跳过绘制形状0

你也会遇到同样的问题xand y,因为状态永远不会改变

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章