• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Start/Stop/Step Loop

 
Kim Mirtens
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • 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?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • 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.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic