user3142972
user3142972

Reputation: 897

Java graphics not updating correctly

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?

Upvotes: 0

Views: 638

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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.

Upvotes: 4

Related Questions