java 如何在循环时暂停直到按下按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14296891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pause while loop until a button is pressed
提问by Rhiokai
How do I pause a while loop until a button is pressed?
如何暂停 while 循环直到按下按钮?
I want to have a while loop which restarts everytime a button is pressed. Is this possible?
我想有一个 while 循环,每次按下按钮时都会重新启动。这可能吗?
回答by syb0rg
Answer 1
答案 1
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
}
}
Answer 2
答案 2
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();
Answer 3
答案 3
Have a loop within the loop
在循环中有一个循环
while(listening) {
while(!buttonPress) {
}
buttonPress=false;
// do stuff
}
回答by Auslay
You could use the following code:
您可以使用以下代码:
(System.in.available() == 0){
//Do whatever you want
}
(System.in.available() == 0){
//Do whatever you want
}
回答by Shreshth Kharbanda
while (button.isPressed()) {
break;
}
while (!button.isPressed()) {
// do your things...
}