How do I pause a while loop until a button is pressed?
I want to have a while loop which restarts everytime a button is pressed. Is this possible?
You could have a button that will exit the loop when it is pressed, and then call the method immediately after it exits.
public void process(){
boolean done = false;
while(!done) {
// do stuff
if (buttonPress) done = true; // ends loop
else buttonPress = false; // insures buttonPress is false, not needed
}
}
You could also just sleep the thread for a certain amount of time, then it will automatically continue when the thread "wakes up".
Thread thread = new Thread() {
boolean isRunning = true;
public void run() {
while(isRunning){
// do stuff
if(buttonPress) Thread.sleep(4000); // or however long you want
}
}
};
thread.start();
Have a loop within the loop
while(listening) {
while(!buttonPress) {
}
buttonPress=false;
// do stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With