繁体   English   中英

如何在循环中暂停直到按下按钮

[英]How to pause while loop until a button is pressed

如何暂停一会儿循环直到按下按钮?

我希望有一个while循环,每次按下按钮时都会重新启动。 这可能吗?

答案1

您可能有一个按钮,该按钮在按下时将退出循环,然后在退出后立即调用该方法。

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
    }
}

答案2

您也可以仅使线程休眠一段时间,然后在线程“唤醒”时它将自动继续。

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();

答案3

循环内有一个循环

while(listening) {
    while(!buttonPress) {
    }
    buttonPress=false;
    // do stuff
}

您可以使用以下代码:

(System.in.available() == 0){ //Do whatever you want }

while (button.isPressed()) {
    break;
} 
while (!button.isPressed()) {
    // do your things...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM