Hello,
I've been trying to draw a kind of recursive tree similar to
this one but I got stuck. I can't write the actual recursion and am asking for some help how to do it.
import java.awt.*;
import javax.swing.*;
public class Tree extends JPanel{
static void drawTree(Graphics2D g, int n, int x, int y,
int x1, int y1, int x2, int y2, int x3, int y3){
if(n==0){
return;
}
else{
g.setColor(Color.BLUE);
g.translate(x, y); // Moves to center of the screen
g.rotate(180*Math.PI/180);
g.drawLine(0, 0, x1, y1);
g.drawLine(0, 0, x2, y2); // Draws main three lines
g.drawLine(0, 0, x3, y3);
g.rotate(-180*Math.PI/180); // Still at the center
g.translate(-x1, -y1); // Moves to the top of the left line
g.rotate(150*Math.PI/180);
g.drawLine(0, 0, x1/2, y1/2);
g.drawLine(0, 0, x2/2, y2/2); // Draws first combination
g.drawLine(0, 0, x3/2, y3/2);
g.rotate(-150*Math.PI/180);
g.translate(x1, y1); // Moves back to center
g.translate(-x2, -y2); // Moves to the top of the middle line
g.rotate(180*Math.PI/180);
g.drawLine(0, 0, x1/3, y1/3);
g.drawLine(0, 0, x2/3, y2/3); // Draws second combination
g.drawLine(0, 0, x3/3, y3/3);
g.rotate(-180*Math.PI/180);
g.translate(x2, y2); // Moves back to center
g.translate(-x3, -y3); // Moves to the top of the right line
g.rotate(210*Math.PI/180);
g.drawLine(0, 0, x1/2, y1/2);
g.drawLine(0, 0, x2/2, y2/2); // Draws third combination
g.drawLine(0, 0, x3/2, y3/2);
g.rotate(-210*Math.PI/180);
g.translate(x3, y3); // Moves back to center
g.setColor(Color.RED);
g.drawLine(0, 0, 50, 0);
g.drawLine(0, 0, 0, 50); // Draws coordinate system just for my reference
g.drawLine(0, 0, -50, 0);
}
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
drawTree((Graphics2D)g, 5, getWidth()/2, getHeight()/2, 40, 20, 10, 15, -40, 20 );
}
public static void main(String[] args) {
Tree panel = new Tree();
JFrame app = new JFrame("Tree");
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.add(panel);
app.setSize(500, 500);
app.setVisible(true);
}
}
For now I don't worry about the stem. Just the branches.
Any help/hints are greatly appreciated.
Edited by: Luke on May 1, 2011 5:04 PM