0

In my program, a the graphics on my screen are supposed to move across the screen. I have a loop that calls the draw function(the draw function is display.draw()), but whenever the amount of times the loop runs is greater than one, the display doesn't update after each time like it should. Instead, it waits until the loop finishes to update the display.

below is the refreshing function that only apparently runs at the end.

public void refresh()
{
    myPanel.removeAll();
    myPanel.add(display.draw());
    myPanel.validate();
    myPanel.repaint();
}

And here's the loop. I added a 1 second sleep after each iteration to make sure it just wasn't moving faster than I could see.

for(int i = 0; i < 2; i++)
{
    myGraphics.rearrange();
    this.refresh();
    try {
        Thread.sleep(1000);
    } catch(InterruptedException e) {
    }
}

myGraphics.rearrange() simply changes the values of the variables which the drawing function uses, changing the x and y variables for the positions of all the objects.

What is happening that it's not updating?

1
  • 1
    This gets asked all the time... you're blocking the event dispatch thread (that's where the drawing would happen, if it could). Use a swing Timer instead. Commented Dec 2, 2014 at 20:46

1 Answer 1

4

You're calling Thread.sleep(...) in a Swing program on the Swing event thread. What this does is put the entire application to sleep and so is not something that you should be doing. Instead use a Swing Timer to drive your animation.

For example:

For more specific help, consider posting more code, preferably an mcve.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.