Gibsdev
Gibsdev

Reputation: 1

Does the repaint() get called automatically sometimes?

I'm making a game. Each object in the game is registered in a registry. I have an update and render method being called by a game loop. The render method calls repaint() on my JPanel and I have overridden paintComponent(Graphics g) for graphics. When it renders and updates, it goes through each object and updates it and renders it from the registry. Sometimes I get a concurrent modification error, and i believe it is because something is calling the paintComponent() other than from my game loop. If a JPanel or even JFrame calls repaint on its own, is there any way to disable it?

Upvotes: 0

Views: 466

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347204

"paintComponent() other than from my game loop"

First, you should never be calling any paint method yourself (even printing should be done via the print methods).

Second, if you call repaint, a paint event will be scheduled by the repaint manager and (eventually) processed by the Event Dispatching Thread. When and how this is done comes down to how the repaint manager schedules these events. This means that all painting is done within the context of the EDT (unless you are doing something you shouldn't be). This means painting is never done from within the context of your game loop

This means, if your changing the state of the game that the paint routines rely on, you will have concurrent issues.

You could synchronize the shared data structures so that they can't be accessed while some other thread is accessing the data.

You could render the state of the to a backing buffer within the game thread, then assign it to a active buffer. Thus is kind of like a double buffering approach

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

No, repaint() doesn't get called automatically, but paint(Graphics g) does at times, and you have no control over this. Also, your repaint() calls may be ignored if they get "stacked". For more on this, please check out this article: Painting in AWT and Swing.

Hopefully you have no program logic inside of your paintComponent method. If you do, get it out of there.

Upvotes: 5

Related Questions