File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Start/Stop/Step Loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Start/Stop/Step Loop" Watch "Start/Stop/Step Loop" New topic

Start/Stop/Step Loop

Kim Mirtens

Joined: Dec 17, 2006
Posts: 21
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

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
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.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
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
before calling
then reset the flag.
I agree. Here's the link:
subject: Start/Stop/Step Loop
jQuery in Action, 3rd edition