import java.awt.*; import java.awt.Frame; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class SierpinskiGasket extends Frame { public SierpinskiGasket() { super("SierpinskiGasket"); setSize(500,500); this.addWindowListener(new WindowListener() { public void windowClosing(WindowEvent e) {System.exit(0);} public void windowClosed(WindowEvent e) {} public void windowOpened(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }); } public static void main(String[] args) { SierpinskiGasket app= new SierpinskiGasket(); app.setVisible(true); } public void paint (Graphics g) { // draw black background square g.setColor(randColor() ); g.fillRect(0, 0, getWidth(), getHeight()); drawGasket(g, 0, 0, Math.min(getHeight(), getWidth())); } public Color randColor() { int r = (int)(256*Math.random()); int g = (int)(256*Math.random()); int b = (int)(256*Math.random()); return new Color(r,g,b); } public void drawGasket(Graphics g, int x, int y, int side) { // draw single white square in middle int sub = side / 3; // length of sub-squares g.setColor(Color.WHITE); g.fillRect(x + sub, y + sub, sub - 1, sub - 1); if(sub >= 3) { // now draw eight sub-gaskets around the white square drawGasket(g, x,y, sub); drawGasket(g, x + sub,y, sub); drawGasket(g, x + 2 * sub, y, sub); drawGasket(g, x,y + sub, sub); drawGasket(g, x + 2 * sub, y + sub, sub); drawGasket(g, x,y + 2 * sub, sub); drawGasket(g, x + sub,y + 2 * sub, sub); drawGasket(g, x + 2 * sub, y + 2 * sub, sub); } } }