import javax.swing.JFrame; //imports for the frame
import java.awt.Color; //imports the colour
import java.awt.Graphics; //imports the graphics
import java.util.Random; // imports the random class for random colour
public class SierpinskiSquare
{
public static void main (String[]args)
{
new SFrame(); // call to the frame, program
}
}
class SFrame extends JFrame
{
Graphics g; // graphics
Color c =Color.WHITE; // set colour to white to creat the blanks
Random r = new Random();
public SFrame()
{
setTitle("Sierpinski Square"); // name of the window/frame
setVisible(true); // true to show the window
setSize(500,500); // creats the frame, starting window visible true
// setResizable(false); //cannot resize the frame/window -- useless, since fratal base is on window size
setLocationRelativeTo(null); //center the frame/window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //exit window, omit this line to avoid annoying pop up, useless
// setBackground(Color.WHITE); //set background to white
}
public void paint(Graphics g)
{
this.g = g;
repaint(); // incase if the window size is change, then "refresh" page, useless since window size never change
drawSierpinskiSquare( 0, 0, getWidth(), getHeight()); // start recursion
}
private void drawSierpinskiSquare ( int x, int y ,int w, int h)
{
if (w>2 && h>2) //control when to stop
{
int nw=w/3, nh=h/3; // the new square's width and height
g.setColor(c); //random colour (default is white)
g.fillRect ( x+nw,y+nh,nw,nh); //draws and fill the square, bigger one
for (int k=0;k<9;k++) // inside the big square, divide it into 9 smaller one equally
if (k!=4) // if is not the middle square
{
c=new Color( r.nextInt(256), r.nextInt(256), r.nextInt(256)); //makes the new colour
int i=k/3, j=k%3; // dividing the 8 equal squares into another 9 smaller ones
drawSierpinskiSquare ( x+i*nw, y+j*nh, nw, nh ); // draws out the recursion
}
}
}
} |