简体   繁体   English

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

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

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. 我希望有一个while循环,每次按下按钮时都会重新启动。 Is this possible? 这可能吗?

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
}

您可以使用以下代码:

(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.

相关问题 暂停一会儿循环,直到在NetBeans中按下确认按钮为止 - Pause a while loop until a confirm button is pressed in NetBeans 如何暂停具有main()的程序,直到按下GUI中的按钮? - How to pause program having main() until a button from GUI is pressed? 如何在按下按钮之前暂停方法? - How do I pause a method until a button is pressed? 如何暂停for循环,直到按下按钮? - How to pause a for loop until a button is presses? 如何在Java的while循环中检查按钮是否按下? - How to check button is pressed or not in while loop in java? 如何使Java程序暂停直到按下特定按钮? - How can I make my Java program pause until a specific button has been pressed? 按下按钮时循环播放声音 - Loop a sound while a button is pressed 我如何使用等待通知来停止在另一个类中等待按下按钮时暂停方法 - how do I use wait notify to stop pause a method while waiting on a button to be pressed in another class 如何在按下按钮时使一段代码循环,并在不再按下按钮时将其停止? - How can I make a piece of code loop while a Button is pressed and stop it once the Button is no longer Pressed? 如何在按下按钮时循环播放声音并在释放时停止播放? - How to loop a sound while button is pressed and stop when released?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM