...

View Full Version : Loop help



chiefbutz
07-09-2008, 02: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)

Aradon
07-09-2008, 03: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.

chiefbutz
07-09-2008, 04: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) {
doWait();
doSound(wheel.nextInt(numBoxes));
}
}

}

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.

brad211987
07-09-2008, 08: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().

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

new doPrac().run();

with


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

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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum