Author Topic: [Java] L- Systems : Tree  (Read 1560 times)

0 Members and 1 Guest are viewing this topic.

Offline Psycho_Coder

  • Knight
  • **
  • Posts: 166
  • Cookies: 84
  • Programmer, Forensic Analyst
    • View Profile
    • Code Hackers Blog
[Java] L- Systems : Tree
« on: October 21, 2013, 10:43:38 pm »

Tree Fractal example code.





Code: [Select]
import java.awt.Color;
import java.awt.Graphics;


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;




/**
 * @author psychocoder
 */
public class L_Systems_Tree extends JPanel {


   private static final long serialVersionUID = 1L;


   public L_Systems_Tree() {
     
   }


   private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {
      if (depth == 0)
         return;
      int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 12.0);
      int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 12.0);
      g.drawLine(x1, y1, x2, y2);
      drawTree(g, x2, y2, angle - 20, depth - 1);
      drawTree(g, x2, y2, angle + 20, depth - 1);
   }


   @Override
   public void paintComponent(Graphics g) {
      g.setColor(Color.DARK_GRAY);
      drawTree(g, getWidth() / 2, getHeight(), -90, 10);
   }


   public static void main(String... args) {
      final JFrame frame = new JFrame("L Systems - Tree Fractal");
      SwingUtilities.invokeLater(new Runnable() {


         @Override
         public void run() {
            frame.setContentPane(new L_Systems_Tree());
            frame.setSize(1000, 700);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setResizable(true);
            frame.setVisible(true);
         }
      });
   }
}
"Don't do anything by half. If you love someone, love them with all your soul. When you hate someone, hate them until it hurts."--- Henry Rollins