Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Thread.sleep() problem

843789Oct 20 2009 — edited Oct 21 2009
Modifying an exercise in Deitel (Java How to program) and can't get Thread.sleep to work. The exercise was to create a square-shaped spiral, which I then modified to run a loop which goes between various numbers of spirals. I know that to slow it down enough that I can see the iterations, I need to use the Thread.sleep() method, yet I can't quite get it working... running the program just causes it to pause until the last screen is drawn. I have tried placing the try/catch block in several different places to no avail.

If you hadn't guessed, I know next to nothing about threads.

Here's the code.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.JFrame;

public class DrawSpiralTest {

	public static void main(String[] args) throws InterruptedException {
		DrawSpiral panel = new DrawSpiral();
		JFrame application = new JFrame();
		
		application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		application.add(panel);
		application.setSize(400, 250);
		application.setVisible(true);
	}

}

class DrawSpiral extends JPanel
{
	public DrawSpiral()
	{
		setBackground(Color.white);
	}
	public void paintComponent(Graphics g) 
	{	
		for (int numSpirals = 6; numSpirals<20; numSpirals++) //without this for loop, just draws numSpirals number of spirals
		{
			super.paintComponent(g);
			int centerX = getWidth() / 2;
			int centerY = getHeight() / 2;
			int xLength = getWidth() / numSpirals;
			int yLength = getHeight() / numSpirals;
			int startX = centerX;
			int startY = centerY;
			int endX = startX;
			int endY;
			g.setColor(Color.black);
			
			for(int i = 1; i<numSpirals+1; i++){ 
				
				startX = endX;
				endY = startY + yLength*i;
				g.drawLine(startX, startY, startX, endY); // draw downward leg
				
				startY = endY;
				endX = startX - xLength*i;
				g.drawLine(startX, startY, endX, endY);  // draw leftward leg
				
				i++;
				startX = endX;
				endY = startY - yLength*i;
				g.drawLine(startX, startY, endX, endY); // draw upward leg
				
				startY = endY;
				endX = startX + xLength*i;
				g.drawLine(startX, startY, endX, endY); // draw rightward leg
				/*  // she no work!!
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {}
				*/
			}		
		}	
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 18 2009
Added on Oct 20 2009
7 comments
1,012 views