import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TreePanel extends JPanel { public static int BEND_ANGLE = 40; // The degree at which each branch bends public static float SHRINK_FACTOR = 0.67f; // The rate (%) at which each recursive branch will shrink public static final int WINDOW_WIDTH = 1200; public static final int WINDOW_HEIGHT = 1200; public TreePanel() { setPreferredSize(new Dimension(WINDOW_WIDTH, WINDOW_HEIGHT)); setBackground(Color.WHITE); } // Display the Tree public void paintComponent(Graphics aPen) { super.paintComponent(aPen); drawTree(100, WINDOW_WIDTH/2, WINDOW_HEIGHT - 100, 90, aPen); } // This code does all the actual recursive drawing of a branch public void drawTree(int length, int x, int y, int dir, Graphics aPen) { if (length < 2) return; ((Graphics2D)aPen).setStroke(new BasicStroke(length*length / 150)); if (length > 10) aPen.setColor(new Color(85, 45, 0)); else aPen.setColor(new Color (0, 80 + (int)(Math.random()*50), 0)); BEND_ANGLE = (int)(10 + Math.random()*30); double stretch = 1 + Math.random()/2; int endX = x + (int)(length * Math.cos(Math.toRadians(dir))); int endY = y + (int)(length * Math.sin(Math.toRadians(dir + 180))); aPen.drawLine(x, y, endX, endY); drawTree((int)(length * SHRINK_FACTOR * stretch), endX, endY, dir - BEND_ANGLE, aPen); drawTree((int)(length * SHRINK_FACTOR * stretch), endX, endY, dir + BEND_ANGLE, aPen); } // Create the panel in a window and make it visible public static void main(String args[]) { JFrame frame = new JFrame("Tree Drawing"); frame.add(new TreePanel()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); // Makes size according to panel's preference frame.setVisible(true); } }