I am relatively new to game development using Java. I have been developing games and studying game development for 2-3 months now.
I have always used Swing for my graphics (aka, the entire game is displayed on a JPanel, using a Graphics2D object). I had no trouble with this up until now.
Very recently, I came across a problem in my most recent project. Some method has problems with being called in consistent time intervals (sometimes it runs every 15-16 milliseconds, as it should, and sometimes it starts to run every 3000 (!) milliseconds).
I did some frustrating debugging and some research, and found out that the reason this happens is probably because I'm not handling Swing and threads right.
My entrie game loop runs inside the run() method of a thread (which is not the EDT). So I'm modifying Swing elements outside of the EDT all of the time. Obviously this was bound to cause problems.
When I found out this was the problem was, I thought:
"Hey, I'll simply use SwingUtilities.invokeLater() in order to run the gameloop inside the EDT!"
But then I remembered, that just as it's 'forbidden' to manipulate Swing elements outside of the EDT, it's also problematic to manipulate non-Swing objects from inside the EDT (I think... is this correct?).
If so, then I have no idea how to develop games in Java using Swing without running into weird problems.
My question is:
How can I develop games safely, using Swing? What would be good guidelines for me to be strict about in order to avoid problems involving Swing and threading? Any instructions every game developer who uses Swing should know?
This is very important for me to understand, since I really want to progress with game development using Java, but if I won't understand this, I'm always going to run into weird problems and won't be able to progress.
Thank you for your help