Hi all, I am doing some swing game programming and I am at a bit of a loss right now as the AWT Event 0 thread ( I have system.out.printed its name) seems to be calling the same code twice, any ideas on this? I am overriding the paintComponent() of JPanel and using this method to draw my game canvas. when the player is called I am calling a method from paintComponent() that disposes the gameJFrame and then launches a new JFrame (a high score frame) - and the high score frame pops up twice!
I am not going to post code at this stage as I am still trying to detect the point at which the thread starts to call the same code twice. any help would be greatly appreciated as this has been a thorn in my side for a while now!

paintComponent() can definitely be called often and you really shouldn't be creating any new components in that method. It should just handling painting the component to the screen. Perhaps you should pop up the other screen from whatever event ended play.

Edit: Just a note on the double call: it's most likely being called a second time because it has to re-render the screen after you pop up a frame on top of it.

Thank you for the reply Ezzaral, that is useful to know. What I have done right now is call sleep(3000) so that the current thread sleeps when player dies. This sleep period does seem sufficient to prevent the pop up occuring twice. Is this a total hack though? Is there a better approach? At present, (I guess this is probably not ideal, from what you said) my game loop is in paintcomponent(), is there a better approach? Thanks again.

You really should have your game loop running in a separate thread, process and update your object interactions in that loop and then repaint(). Leave paintComponent() to its intended purpose of just rendering that component on the screen.

Here are a couple of tutorials on game/animation rendering if you'd like to see some alternatives:
http://www.cokeandcode.com/spaceinvaderstutorial
http://www.developer.com/java/other/article.php/893471/Fun-with-Java-Sprite-Animation-Part-1.htm

Thanks very much Ezzaral, this is quite a learning experience! A good one though!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.