View Full Version : Loop help

07-09-2008, 03:24 AM
Alright, in my program I have a GUI and when you click a button a loop starts. Is there anyway to isolate that loop so that another button can be click to stop it? I have tried putting the loop in a separate thread, but I don't think that is what I need (or I did it wrong and it still ran without error)

07-09-2008, 04:25 AM
Without seeing code it's hard to say. But putting the loop in another thread waiting for a signal from your parent thread _should_ work. So if there is still an error then it is most likely some type of coding error, which we will need to see code for.

07-09-2008, 05:18 AM
I guess code would be helpful wouldn't it. Alrighty, here we go.

This is the function that I need to have in a different thread.

private class doPrac implements Runnable
public void run() {
Random wheel = new Random();
while(!stopLoop) {


This is where my listener goes for the button click:

private class Practice implements ActionListener {

public void actionPerformed(ActionEvent arg0) {
new doPrac().run();


In theory the loop is in a different thread. Oh, and stopLoop is a class wide variable that is changed by the stop button.

07-09-2008, 09:42 PM
If I understand it right, its actually not in another thread. You should be able to create a thread and pass your doPrac object to it as it already implement the Runnable interface. Should only need to create the thread and then call threan.start().

07-09-2008, 11:42 PM
That did it. All I had to do was replace

new doPrac().run();


new Thread(new doPrac()).start();

thank you for your help. I now know how to do threads (I had never used them before)