thread-safe graphics access
In a book on Java game programming, I found a game that uses a
component (called ?this? below), which is a JPanel.
This component has a custom thread to update it.
This thread, simplified, does this to update the game display:
this.getGraphics().drawImage( gameImage, 0, 0, null );
I notice that this is an access of a Swing component from
within the custom thread, outside of the EDT, though I am not
sure what constitutes the actual offending access
(?getGraphics? or ?drawImage?).
An older Sun tutorial says:
?Swing components can be accessed by only one thread at a time.
Generally, this thread is the event-dispatching thread.?
So, can I get by without using ?InvokeAndWait?, when I am
confident that no one else is accessing the graphics object of
my custom component at this time?
- I can make sure that no other thread of my program
accesses this JPanel.
- I do not expect Swing to draw to the graphics object
of this component.
But what happens, if a Swing menu is added to the program,
gets openend and then overlaps this custom component?
So, in the end, I should wrap this access with an invoke
method?
The whole game is a kind of loop:
while( running)
{ update( gameImage );
this.getGraphics().drawImage( gameImage, 0, 0, null ); }
So, if I have to wrap the final statement, how do I do this?
My first impression is that this needs ?InvokeAndWait?,
because this is most close to the original behavior as shown
above. Or may/should I use ?InvokeLater? in this case?