import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;



@SuppressWarnings("serial")
public class DrawingCanvas extends JComponent {
	
	/* This paint function draws a fractal tree -- Google "L-systems" for 
	 * more explanation / inspiration.
	 * It is the same as the fractal drawing from the OCaml lecture. */
	private static void fractal(Graphics gc, int x, int y, double angle, double len) {
		if (len > 1) {
			double af = (angle * Math.PI) / 180.0;
			int nx = x + (int)(len * Math.cos(af));
			int ny = y + (int)(len * Math.sin(af));
			gc.drawLine(x, y, nx, ny);
			fractal(gc, nx, ny, angle + 20, len - 2);
			fractal(gc, nx, ny, angle - 10, len - 1);
		}
	}
	
	
	public void paintComponent(Graphics gc) {
		super.paintComponent(gc);
		
		// set the pen color to green
		gc.setColor(Color.GREEN);
		
		// draw a fractal tree
		fractal (gc, 75, 100, 270, 15);
	}
	
	// get the size of the drawing panel
	public Dimension getPreferredSize() {
		return new Dimension(150,150);
	}
	
	public static void main(String[] args) {
		// a frame is a top-level window
		JFrame frame = new JFrame("Tree");
		
		// set the content of the window to be the drawing
		frame.add(new DrawingCanvas());
		
		// make sure the application exits when the frame closes
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// resize the frame based on the size of the canvas
		frame.pack();
		
		// show the frame
		frame.setVisible(true);
	}

}

