I'm trying to create a simple game using Java 2D. I keep running into this frustrating problem though.
I'm storing all of the on-screen entities in a LinkedList (they might represent spaceships, bullets, whatever). In the main loop of my program, the list is iterated through, and each entity is given the chance to move. Once this is done, I call "repaint" on a JPanel that I've subclassed. The "paintComponent" method has been overridden to iterate through the LinkedList of entities, passing each one the "Graphics2D" object and allowing them to draw themselves.
This works fine, until I need to modify the LinkedList. (I've got a KeyListener setup to add a new entity when the user presses the space bar for example). When this happens though, sometimes I get a ConcurrentModificationException.
I assume this is happening because the KeyListener is running on a separate thread, and is modifying the LinkedList while it's being iterated through in the main loop or in "paintComponent". I suspect I'll encounter similar problems when I want to remove entities (e.g. I remove an entity in the main loop, but paintComponent is accessing the list at the same time in a separate thread).
I know almost nothing about multithreading, so I have no idea what to do about this. Is there a quick fix, or do I need to go back and learn about multithreading? A quick fix would be nice, I just want to get my game working at the moment!