• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Program logic runs but graphics freeze

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi there,

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!!!


 
Rancher
Posts: 3324
32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic