Win a copy of Practice Tests for OCP Java 17 Certification Exam (1Z0-829) this week in the OCPJP forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

Start/Stop/Step Loop

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a program with 3 buttons, namely start/stop/step. I have a loop which moves a circle around on a JPanel. I want the loop to be started when the user presses "start" and the loop to "stop" when the user presses stop (the program has to remember the current state of the loop). When the users presses start again the loop has to start where it left of. When the user presses "step" the loop has to make one step in the loop (step will only be possible when the loop is stopped).
What is the easiest way to do this? Do I need to threat my program to listen to the buttons while my loop is running?
 
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you need something to change over time once you press your Start button, then yes, you need to use threads; either explicitly, or implicitly using the javax.swing.Timer class.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, you basically would have a thread running that animates the circle. (You might want to use a Timer or something.)

The Buttons would change the state of a model, which the timer uses to determine what exactly it should do.
 
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if the circle is drawn via paintComponent(), the timer would only modify
the x and y coordinates then call repaint(), thus the state would be remembered.

the step function would set
timer.setRepeats(false);
before calling
timer.start();
then reset the flag.
 
reply
    Bookmark Topic Watch Topic
  • New Topic