import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JPanel; import javax.swing.JFrame; public class TreeFractal extends JPanel implements MouseMotionListener { public static int WIDTH=800; public static int HEIGHT=800; public TreeFractal() { } public static void main(String[] args) { TreeFractal app= new TreeFractal(); JFrame window = new JFrame("Tree Fractal"); window.setSize(WIDTH, HEIGHT); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.getContentPane().add(app); window.getContentPane().addMouseMotionListener(app); window.setVisible(true); } public void paintComponent (Graphics g) { super.paintComponent(g); drawTree(g, getWidth()/2.0, getHeight()*.95, getHeight()/4.0, Math.PI/2.0); } public void drawTree(Graphics g, double x, double y, double len, double angle) { if(len >2){ double nextX= x + len* Math.cos(angle); double nextY= y - len* Math.sin(angle); g.setColor(randColor()); g.drawLine((int)Math.round(x), (int)Math.round(y), (int)Math.round(nextX), (int)Math.round(nextY) ); drawTree(g, nextX, nextY, len * 0.75, angle + Math.PI/6.0); drawTree(g, nextX, nextY, len * 0.66, angle - 5.0*Math.PI/18.0); } } /** * This is a random Color which favors browns and greens... */ public Color randColor(){ int r=32+(int)(Math.random()*128); int g=64+(int)(Math.random()*128); int b=16+(int)(Math.random()*64); return new Color(r,g,b); } /** * These are the Methods needed to implement the MouseMotionListener Interface */ @Override public void mouseDragged(MouseEvent e) { repaint(); } @Override public void mouseMoved(MouseEvent e) { repaint(); } }