The call to repaint
will not immediately cause the component to be repainted. It only tells the rendering system: "Repaint this area as soon as possible". But the rendering system is busy with iterating through your for
loop.
The reason is that the mousePressed
method is executed by the same thread that is also responsible for repainting - namely by the Swing Event Dispatch Thread (EDT). So this thread is running through your for
loop and triggering repaints, but only after it has finished the for
loop it is able to actually execute the repaint - and then, only the last state will be visible.
The solution here should be to execute the movement in an own thread. The straightforward solution could look like this
public void mousePressed(MouseEvent e)
{
moveInOwnThread();
}
private void moveInOwnThread()
{
Thread t = new Thread(new Runnable()
{
@Override
public void run()
{
move();
}
});
t.setDaemon(true);
t.start();
}
private void move()
{
for(int i=0;i<10;i++)
{
moveSquare(redSquare.getX(),redSquare.getY());
try
{
Thread.sleep(20);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
return;
}
}
}
But you should read something about concurrency in swing: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/