The following is from the article link in the previous post.
example code of the game loop in it’s most simplest form:
1 2 3 4 5 6
| bool game_is_running = true;
while( game_is_running ) { update_game(); display_game(); } |
The problem with this simple loop is that it doesn’t handle time, the game just runs.
I'm in a minority, but I think an entirely reasonable alternative is to consider using a single java.util.Timer to run the game loop. It's not that hard to set up an "Observer" design pattern to subscribe and unsubscribe all objects or processes that need animation ticks. I started an example in the Tutorials section but haven't had time to make the revisions to put it in an easier-to-read format. One big plus: new loops start at regular intervals without any need to further manage the amount of code that runs within each animation cycle (as long as you don't try to animate 10,000 objects and start overshooting the cycle time). Seems to scale well.
If you don't want to deal with the Observer pattern, this is even simpler, and gives a steady 40 updates a second (well actually a little less, but still reasonably steady):
1 2
| Timer timer = new Timer(); timer.schedule(new RemindTask(), 25, 25); |
and
1 2 3 4 5 6
| class RemindTask() extends TimerTask { public void Run() { updateGame(); yourJPanelOrWhatever.repaint(); } } |
It's not that hard to set it up so that you can turn the Timer on or off as needed. And the repaints occur often enough you probably won't need to add any more of them to the response code for the various listeners.