I'm wondering why Thread.sleep()
does not strike in the expected point of time.
I expected the first rectangle to be drawn, a pause of 2 seconds and then the appearance of the second rectangle. However, the pause kicks in first and then both rectangles are drawn 'at once'.
Why does this happen to be the case?
Thanks in advance for any advices.
public class Figure extends JPanel
{
Point a = new Point(10, 10);
Point b = new Point(110, 10);
Point c = new Point(110, 110);
Point d = new Point(10, 110);
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(a.x, a.y, b.x, b.y);
g.drawLine(b.x, b.y, c.x, c.y);
g.drawLine(c.x, c.y, d.x, d.y);
g.drawLine(d.x, d.y, a.x, a.y);
try
{
Thread.sleep(2000);
}
catch(InterruptedException ex)
{
}
Point newA = rotate(a, 45);
Point newB = rotate(b, 45);
Point newC = rotate(c, 45);
Point newD = rotate(d, 45);
g.drawLine(newA.x, newA.y, newB.x, newB.y);
g.drawLine(newB.x, newB.y, newC.x, newC.y);
g.drawLine(newC.x, newC.y, newD.x, newD.y);
g.drawLine(newD.x, newD.y, newA.x, newA.y);
}
private Point rotate(Point p, int degree)
{
//to shift the resulting Point some levels lower
int offset = 100;
int x = (int)(Math.cos(degree) * p.x + Math.sin(degree) * p.y);
int y = (int)(-Math.sin(degree) * p.x + Math.cos(degree) * p.y) + offset;
Point ret = new Point(x, y);
return ret;
}
}