I've taken up the challenge of creating a basic 2D side-scrolling monster truck game for my little brother. It seems easy enough in theory, but jumping into Java out of XNA feels strange.
My game class has a private class GameLoop
extending Runnable
. In the overridden run()
method, a while
-loop handles time and such. There's a targetFPS
for drawing as well. The loop looks like this:
public void run()
{
long fpsTime = 0;
gameStart = System.currentTimeMillis();
lastTime = System.currentTimeMillis();
while(game.isGameRunning())
{
currentTime = System.currentTimeMillis();
long ellapsedTime = currentTime - lastTime;
if(mouseState.leftIsDown)
{
que.add(new Dot(mouseState.getPosition()));
}
entities.addAll(que);
game.updateGame(ellapsedTime);
fpsTime += ellapsedTime;
if(fpsTime >= (1000 / targetedFPS))
{
game.drawGame(ellapsedTime);
}
lastTime = currentTime;
}
I'm running into a problem when adding entities after a click. I made a class with a private class extending MouseListener
and MouseMotionListener
, then on changes I have it set a few booleans to tell me if the mouse is pressed or not which seems to work great. However, when I add the entity, I occasionally get a CME (Concurrent Modification Exception). All the entities are stored in a LinkedList<Entity>
.
I also tried adding a queued LinkedList
, where I add the contents of the queue to the normal list later in the update loop.
I think this would work fine if it was just the update method in the game loop, but it's the repaint()
method (called from game.drawGame()
) that throws the CME.
The only other thing is that I'm currently drawing directly from the overridden paintComponent()
method in a custom class extending JPanel
.
Is a better way to go about this? How do I fix the CME?