Advertisement
Guest User

sierpinski in java

a guest
May 13th, 2012
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.56 KB | None | 0 0
  1. import java.awt.*;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import java.awt.event.ItemEvent;
  5. import java.awt.event.ItemListener;
  6. import java.util.ArrayList;
  7. import java.util.Random;
  8.  
  9. import javax.swing.*;
  10.  
  11. public class SierpinskiGUI {
  12.     private JFrame frame;
  13.     private JPanel superPanel, rightPanel, textFieldPanel, pickersPanel;
  14.     private Canvas canvas;
  15.     private JLabel textFieldLabel;
  16.     private JTextField textField;
  17.     private JCheckBox randomizeBox;
  18.     private JButton drawButton;
  19.     private MyColor[] colors;
  20.     private ArrayList<Triangle> triangles;
  21.     private ColorSelector[] colorSelector;
  22.     private boolean randomColors;
  23.     private int totalDepth;
  24.     private final int cSize = 512;
  25.  
  26.     /**
  27.      * @author phil
  28.      *
  29.      * Holds the data for one triangle.
  30.      */
  31.     private class Triangle {
  32.         private Color color;
  33.         private int[] xvals;
  34.         private int[] yvals;
  35.         private Polygon triangle;
  36.  
  37.         /**
  38.          *
  39.          * Make a triangle with a specified color.
  40.          *
  41.          * @param d
  42.          * @param x
  43.          * @param y
  44.          * @param S
  45.          * @param color
  46.          */
  47.         Triangle(int d, int x, int y, int S, Color color) {
  48.             this.xvals = new int[3];
  49.             this.yvals = new int[3];
  50.             this.color = color;
  51.  
  52.             if (d == -1) {
  53.                 xvals[0] = x;
  54.                 yvals[0] = y + S; // bottom left
  55.                 xvals[1] = x + S;
  56.                 yvals[1] = y + S; // bottom right
  57.                 xvals[2] = x + (S / 2);
  58.                 yvals[2] = y; // top
  59.             } else {
  60.                 xvals[0] = x + S / 2;
  61.                 yvals[0] = y + S; // bottom
  62.                 xvals[1] = x + S / 4;
  63.                 yvals[1] = y + S / 2; // top left
  64.                 xvals[2] = x + 3 * S / 4;
  65.                 yvals[2] = y + S / 2; // top right
  66.             }
  67.  
  68.             this.triangle = new Polygon(xvals, yvals, 3);
  69.         }
  70.  
  71.         /**
  72.          *
  73.          * Make a triangle and assign the color automatically.
  74.          *
  75.          * @param d
  76.          * @param x
  77.          * @param y
  78.          * @param S
  79.          */
  80.         Triangle(int d, int x, int y, int S) {
  81.  
  82.             this(d, x, y, S, Color.black);
  83.             int colorNum;
  84.             if (randomColors == false) {
  85.  
  86.                 colorNum = totalDepth - d;
  87.                 colorNum = colorNum % 5;
  88.  
  89.                 this.color = colorSelector[colorNum].getColor();
  90.             } else {
  91.                 colorNum = totalDepth - d;
  92.                 this.color = colors[colorNum].getColor();
  93.             }
  94.             // System.out.printf("Auto selecting color %d: %s%n",colorNum,colors[colorNum].toString());
  95.         }
  96.  
  97.         /**
  98.          * @return The color of the triangle
  99.          */
  100.         public Color getColor() {
  101.             return this.color;
  102.         }
  103.  
  104.         /**
  105.          * @return The polygon object for this triangle
  106.          */
  107.         public Polygon getPolygon() {
  108.             return this.triangle;
  109.         }
  110.  
  111.         /**
  112.          * @param color The color to set for this triangle.
  113.          */
  114.         public void setColor(Color color) {
  115.             this.color = color;
  116.         }
  117.     }
  118.  
  119.     /**
  120.      * @author phil
  121.      * Includes a corresponding JComboBox and JLabel for the color selector.
  122.      *
  123.      */
  124.     private class ColorSelector {
  125.         private JLabel text;
  126.         private JComboBox comboBox;
  127.  
  128.         /**
  129.          * @param number Number of the box, e.g. Color 1
  130.          */
  131.         ColorSelector(int number) {
  132.             text = new JLabel("Color " + (number + 1));
  133.             comboBox = new JComboBox(colors);
  134.             comboBox.setSelectedIndex(number);
  135.         }
  136.  
  137.         public JComboBox getComboBox() {
  138.             return comboBox;
  139.         }
  140.  
  141.         public JLabel getText() {
  142.             return text;
  143.         }
  144.  
  145.         /**
  146.          * @return The Color object for the selected color
  147.          */
  148.         public Color getColor() {
  149.             MyColor theMyColor;
  150.  
  151.             theMyColor = (MyColor) comboBox.getSelectedItem();
  152.             return theMyColor.getColor();
  153.         }
  154.     }
  155.  
  156.     /**
  157.      * Start the program
  158.      * @param args none
  159.      */
  160.     public static void main(String[] args) {
  161.         new SierpinskiGUI();
  162.     }
  163.  
  164.     /**
  165.      * Contains a Color and a String for the name.
  166.      * @author phil
  167.      *
  168.      */
  169.     private class MyColor {
  170.         private String name;
  171.         private Color color;
  172.  
  173.         MyColor(String name, Color color) {
  174.             this.name = name;
  175.             this.color = color;
  176.         }
  177.  
  178.         public Color getColor() {
  179.             return color;
  180.         }
  181.  
  182.         public String toString() {
  183.             return name;
  184.         }
  185.     }
  186.  
  187.     /**
  188.      * @return Array of the available colors.
  189.      */
  190.     public MyColor[] getColors() {
  191.         return colors;
  192.     }
  193.  
  194.    
  195.     /**
  196.      * Set up colors to have the predefined Java colors.
  197.      */
  198.     private void setupColors() {
  199.         colors = new MyColor[13];
  200.         colors[0] = new MyColor("Blue", Color.blue);
  201.         colors[1] = new MyColor("Cyan", Color.cyan);
  202.         colors[2] = new MyColor("Dark Grey", Color.darkGray);
  203.         colors[3] = new MyColor("Grey", Color.gray);
  204.         colors[4] = new MyColor("Green", Color.green);
  205.         colors[5] = new MyColor("Light Grey", Color.lightGray);
  206.         colors[6] = new MyColor("Magenta", Color.magenta);
  207.         colors[7] = new MyColor("Orange", Color.orange);
  208.         colors[8] = new MyColor("Pink", Color.pink);
  209.         colors[9] = new MyColor("Red", Color.red);
  210.         colors[10] = new MyColor("White", Color.white);
  211.         colors[11] = new MyColor("Yellow", Color.yellow);
  212.         colors[12] = new MyColor("Black", Color.black);
  213.         randomColors = false;
  214.     }
  215.  
  216.     /**
  217.      * Change the colors[] array to have a set of random MyColors.
  218.      */
  219.     private void setupRandomColors() {
  220.  
  221.         int[] rgb;
  222.         rgb = new int[3];
  223.         Random rng = new Random();
  224.  
  225.         colors = new MyColor[13];
  226.         for (int i = 0; i < 13; i++) {
  227.  
  228.             rgb[0] = rng.nextInt(256);
  229.             rgb[1] = rng.nextInt(256);
  230.             rgb[2] = rng.nextInt(256);
  231.             String name = "" + rgb[0] + "," + rgb[1] + "," + rgb[2];
  232.             colors[i] = new MyColor(name, new Color(rgb[0], rgb[1], rgb[2]));
  233.             randomColors = true;
  234.         }
  235.     }
  236.  
  237.     /**
  238.      *  Make all the frames and panels.
  239.      */
  240.     private void buildGUI() {
  241.         setupColors();
  242.  
  243.         frame = new JFrame("Sierpinski Visualizer");
  244.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  245.         frame.setLayout(new FlowLayout());
  246.  
  247.         // set up the Canvas
  248.         superPanel = new JPanel(); // (new GridLayout(1, 2));
  249.         superPanel.setLayout(new BoxLayout(superPanel, BoxLayout.X_AXIS));
  250.         canvas = new Canvas();
  251.         canvas.setSize(cSize, cSize);
  252.         canvas.setBackground(Color.BLACK);
  253.  
  254.         superPanel.add(canvas);
  255.  
  256.         // Everything but the Canvas goes in this JPanel
  257.         rightPanel = new JPanel();
  258.         rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
  259.         // set up the Recursive Depth entry
  260.         textFieldPanel = new JPanel(new FlowLayout());
  261.         textFieldLabel = new JLabel("Recursive Depth:");
  262.         textField = new JTextField(10);
  263.         textFieldPanel.add(textFieldLabel);
  264.         textFieldPanel.add(textField);
  265.         rightPanel.add(textFieldPanel);
  266.  
  267.         // set up the pickers
  268.         pickersPanel = new JPanel();
  269.         pickersPanel.setLayout(new GridLayout(5, 2));
  270.         // pickersPanel.setLayout(new FlowLayout());
  271.         colorSelector = new ColorSelector[5];
  272.         for (int i = 0; i < 5; i++) {
  273.             colorSelector[i] = new ColorSelector(i);
  274.             // colorSelector[i].getComboBox().setvalue(i);
  275.             pickersPanel.add(colorSelector[i].getText());
  276.             pickersPanel.add(colorSelector[i].getComboBox());
  277.         }
  278.         rightPanel.add(pickersPanel);
  279.  
  280.         randomizeBox = new JCheckBox("Randomize colors at each level");
  281.         randomizeBox.addItemListener(new ItemListener() {
  282.             public void itemStateChanged(ItemEvent e) {
  283.                 if (e.getStateChange() == ItemEvent.SELECTED) { // randomize colors
  284.                     for (ColorSelector c : colorSelector) {
  285.                         c.getComboBox().setEnabled(false);
  286.                         setupRandomColors();
  287.                     }
  288.                 } else {
  289.                     for (ColorSelector c : colorSelector) { // use colors from boxes.
  290.                         c.getComboBox().setEnabled(true);
  291.                         setupColors();
  292.                     }
  293.                 }
  294.  
  295.             }
  296.         });
  297.         drawButton = new JButton("Draw!");
  298.         drawButton.addActionListener(new ActionListener() {
  299.             public void actionPerformed(ActionEvent e) {
  300.                 int depth;
  301.                 try {
  302.                     depth = Integer.parseInt(textField.getText()); // check 1-10 and number.
  303.                     if (depth < 1 || depth > 10)
  304.                         throw (new NumberFormatException());
  305.                 } catch (NumberFormatException x) {
  306.                     JOptionPane.showMessageDialog(frame, "Please input a number from 1 to 10.");
  307.                     return;
  308.                 }
  309.  
  310.                 doDraw(depth);
  311.  
  312.             }
  313.         });
  314.         rightPanel.add(randomizeBox);
  315.         rightPanel.add(drawButton);
  316.         superPanel.add(rightPanel);
  317.         frame.add(superPanel);
  318.         frame.pack();
  319.         frame.setVisible(true);
  320.     }
  321.  
  322.     /**
  323.      * Wrapper for the recursive draw() method
  324.      * @param depth
  325.      */
  326.     private void doDraw(int depth) {
  327.         Graphics g = canvas.getGraphics();
  328.         if (randomColors == true)
  329.             setupRandomColors();
  330.         g.setColor(Color.black);
  331.         g.fillRect(0, 0, cSize, cSize);
  332.         triangles.clear();
  333.         // System.out.println("------------------------------------------------------");
  334.         this.totalDepth = depth; // for calculating the correct color
  335.         // Draw the outside polygon outline
  336.         Triangle outer = new Triangle(-1, 0, 0, cSize);
  337.         g.setColor(Color.white);
  338.         g.drawPolygon(outer.getPolygon());
  339.  
  340.         draw(depth, 0, 0, cSize); // create the triangles.
  341.  
  342.         for (Triangle t : triangles) { // draw the triangles.
  343.             g.setColor(t.getColor());
  344.  
  345.             g.fillPolygon(t.getPolygon());
  346.         }
  347.         System.out.printf("%d triangles.%n",triangles.size());
  348.     }
  349.  
  350.     /**
  351.      * Constructor called from main
  352.      *
  353.      */
  354.     SierpinskiGUI() {
  355.         triangles = new ArrayList<Triangle>();
  356.         buildGUI();
  357.     }
  358.  
  359.     /**
  360.      * Recursive function to create Triangles.
  361.      * @param d
  362.      * @param x
  363.      * @param y
  364.      * @param S
  365.      */
  366.     private void draw(int d, int x, int y, int S) {
  367.         // Done drawing, stop.
  368.         if (d == 0)
  369.             return;
  370.         // Otherwise, draw big triangle at this level, between the points
  371.         // shown in the figure. You can use the fillPolygon() method of
  372.         // the Graphics object of your Canvas. Make sure you get the color
  373.         // right!
  374.         /* <INSERT YOUR CODE HERE> */
  375.         triangles.add(new Triangle(d, x, y, S));
  376.         // Draw the subtriangles. The self-similarity of fractals means
  377.         // that they are themselves Sierpinski triangles of depth d-1.
  378.         draw(d - 1, x + S / 4, y, S / 2);
  379.         draw(d - 1, x, y + S / 2, S / 2);
  380.         draw(d - 1, x + S / 2, y + S / 2, S / 2);
  381.     }
  382. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement