Search code examples
javaswingrecursionjframefractals

Using recursion in method paint() for fractal


I'm learning recursion and I'm trying to make a fractal H-tree using java. I have my method called simple H which makes the H tree of order 1. The head of my method is this one:

public void simpleH(Graphics g, int x, int y, int size){
    g.drawLine(x, y, x, y+tamaño); //right
    g.drawLine(x, y+tamaño/2, x+tamaño, y+tamaño/2); //middle
    g.drawLine(x+tamaño,y,x+tamaño,y+tamaño); //left
}

What I'm trying to do is using the paint() method to redraw the H tree using a recursive method but I'm stuck because I can't find the way to call my simpleH method to draw a H tree in order 2,3,4 depending on what the user inputs. AlSO, I'm struggling because I cant call the paint() method to draw the lines. Anyone can give me some hints?

public void paint(Graphics g,int n, int x, int y, int size){
    if(n==0){
        return;
    }
int x1 = x-size/2;
    int y1=y;
    int x2=x+size/2;
    int y2=y;
    g.drawLine(x1, y1, x2, y2);

    //left line
    y1 = y-size/2;
    x2=x1;
    y2=y+size/2;
    g.drawLine(x1, y1, x2, y2);

    //left recursion
    paint(g,n-1,x1,y1,size/2);
    paint(g,n-1,x2,y2,size/2);

    //right line
    x1=x+size/2;
    x2=x;
    g.drawLine(x1, y1, x2, y2);

    //right recursion
    paint(g,n-1,x1,y1,size/2);
    paint(g,n-1,x2,y2,size/2);

Solution

  • You are overloading the paint() method, therefore swing won't know that it is the paint method it has to use. If you want to overload it anyway just add:

    public void paint(Graphics g){
        paint(g,n,x,y,size);//Place here your initial values
    }
    

    You could just create a new method name and add it to the paint method for clarity tho.

    This way you will get it painted.

    As for the recursion to draw the tree, you could go like:

    public void simpleH(Graphics g, int x, int y, int tamaño, int steps){
        if (steps == 0)
            return;
        g.drawLine(x, y, x, y+tamaño); //right
        g.drawLine(x, y+tamaño/2, x+tamaño, y+tamaño/2); //middle
        g.drawLine(x+tamaño,y,x+tamaño,y+tamaño); //left
    
        //TopLeft
        simpleH(g,x-tamaño/4,y+tamaño*3/4,tamaño/2,steps-1);
        //BottomLeft
        simpleH(g,x-tamaño/4,y-tamaño/4,tamaño/2,steps-1);
        //TopRight
        simpleH(g,x+tamaño*3/4,y+tamaño*3/4,tamaño/2,steps-1);
        //BottomRight
        simpleH(g,x+tamaño*3/4,y-tamaño/4,tamaño/2,steps-1);
    }
    

    Since you had set the origin of each H at the bottom left corner, to get the new origin for the new ones, you have to move it's X to the left half its future size:

    x - tamaño/2/2 -> (x - tamaño/4) for left side.

    x + tamaño- tamaño/2/2 -> (x + tamaño *3/4) for right side.

    Same goes for the Y coordinate, y - tamaño/4 for the bottom and y + tamaño * 3/4 for the top.

    Don't forget to set a limit to the recursion or you'll run off memory.