Here's a really pointless piece of code (hey, it was suggested by Deitel in JHTP!) that has a quirk I can't figure out. Basically, it's the old tortoise and hare race, with lovely icons running up the hill... so I got the program logic to work first, then the graphics, then implemented a JButton with an ActionListener which is supposed to restart the run() method. And, it does... I can see by the terminal output that the program is running again. However, the graphics freeze and don't restart. Any suggestions? I tried to attach the graphics as a zipped file but am told I can't. Thanks for wasting your time!!!
posted 6 years ago
Read the secton from the Swing tutorial on "Concurrency".
When you press the button to run the game, the code executes on the EDT which is the Thread that Swing uses to repaint the components. You keep telling the Thread to sleep so it can't repaint anything until the whole loop finishes executing. The System.out.println(...) executes in a separate Thread so the text is still displayed on the terminal.
When you start the program and your code is executing in a normal AWT Thread so the sleep doesn't NOT cause the EDT to sleep so the GUI can repaint itself.
A better way to write the code is to start a Swing Timer to schedule the animation. The tutorial also has a section on using Timers.