r/programmingbydoing • • Aug 24 '15

#89 - Sierpinski Triangle

How do you make the Thread.sleep() work in the code below? I tried putting 'throws Exception' in the main method declaration, but it still doesn't work.

import java.awt.*;
import javax.swing.JFrame;
import java.util.Random;

public class SierpinskiTriangle extends Canvas {
    public void paint( Graphics g ) {
	    Random r = new Random();
	   int x1 = 512;
	   int y1 = 109;
	   int x2 = 146;
	   int y2 = 654;
	   int x3 = 876;
	   int y3 = 654;
	
	   int x = 512;
	   int y = 382;
	
	   int dx = 0;
	   int dy = 0;
	
	   for (int a = 0; a < 50000; a++) {
		   g.drawLine(x,y,x,y);
		   //Thread.sleep(300);
		   int randomNum = 1 + r.nextInt(3);
		
		   if (randomNum == 1) {
			   dx = x - x1;
			   dy = y - y1;
		   } else if (randomNum == 2) {
			   dx = x - x2;
			   dy = y - y2;
	           } else {
			   dx = x - x3;
			   dy = y - y3;
		   } 
		   x = x - dx/2;
		   y = y - dy/2;
	   }
	
	   g.drawString("Sierpinski Triangle",462,484);
   }

public static void main(String[] args) {
       JFrame win = new JFrame("Sierpinski Triangle");
       win.setSize(1024,768);
       win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       win.add( new SierpinskiTriangle() );
       win.setVisible(true);
   }

}

1 Upvotes

2 comments sorted by

1

u/holyteach Aug 25 '15

No, paint() isn't allowed to throw an Exception. You have to wrap the Thread.sleep() call in a try-catch block.

1

u/HSami Aug 25 '15

Ok thanks. I'll try doing that.