1985 All American 2175 Posts user info edit post |
It seems pretty simple, but I cant seem to find an answer anywhere.
I have some while loop that generates certain integers and saves them to a text file. It starts when I click a JButton, and I want to get it to stop when I click another button.
The problem is to generate the numbers, it runs in a while loop and never pauses to check to see if the stop button has been pressed. Is there anyway I can do this? (I thought maybe running it on a different thread)
Thanks. 7/6/2008 12:57:34 AM |
afripino All American 11425 Posts user info edit post |
global variable. instantiate a boolean set to false in your constructor that changes when the button is pushed.
you can then add this into your while loop: if(myButtonBoolean == true){ break; }
this is by no means the only way, just a quick one. 7/6/2008 9:41:43 AM |
1985 All American 2175 Posts user info edit post |
Well, the problem is it doesn't even allow my second button to be pressed in order to change my boolean.
Its set up something like
StartBtnListener implements ActionListener{ . . . generate(candidate); //starts the infinite while loop }
So the program never really 'exits' from the start button being pressed (it still even appears depressed on my gui) 7/6/2008 12:19:20 PM |
afripino All American 11425 Posts user info edit post |
hmm...that's a good one
[Edited on July 6, 2008 at 4:46 PM. Reason : ] 7/6/2008 4:39:06 PM |
1985 All American 2175 Posts user info edit post |
I figured out a way to do it (though, maybe not the best.) I'll post for reference.
I created a new instance of generator and ran it on a separate thread.
Generate generator = new Generate(); Thread genThread= new Thread(generator); genThread.start();
you have to add a few things to Generate(), but its pretty simple and works. Not sure how it effects the efficiency of what im doing though. 7/6/2008 8:02:24 PM |
moron All American 34142 Posts user info edit post |
A new thread is the best way to do this (especially since you don't really have any locking issues). You also could have made the loop itself check to see if the button had been pressed again. 7/7/2008 10:18:10 PM |
afripino All American 11425 Posts user info edit post |
oh yeah...multithreading.... 7/7/2008 10:49:48 PM |
Shaggy All American 17820 Posts user info edit post |
have a boolean running in your thread class. In the run method do
while(running) { try { do stuff } catch(Interrupt exception) { running=false } }
or something like that. When you press the start button it does thread.start. When you press stop it does thread.interrupt.
The thread handles the interrupt and breaks itself out of the loop instead of doing something nasty. 7/8/2008 11:42:37 AM |