How do you temporarily pause a loop until a button is pressed in java

Related searches

How can I make a loop temporarily pause while i wait for a button to be pressed? Iv been looking around for a while, and I cant seem to find it, thought I would try here.

EDIT-

I am creating a blackjack game, I added a gui to it with buttons, HITME and STAND once the game gets to the point in the loop where i need to get player input to either, HITME or STAND I added buttons to execute that, but I cant figure out how to pause the loop to check and see if the button was pressed, and which one to continue.

what i have tried is this:

 (othercode)  
g.printPlayerCards(p1);
            g.totalworth(p1);
            thing.messagetop("Your total card amount is: " + p1.getTotalWorth());
            thing.messagetop("Hit me? or stay?");
            thing.waitonbutton();


public void waitonbutton(){
        wantingtobeclick = 1;
        do{
            while(!(hitme == 0)){
                hitme = 0;
                wantingtobeclick =0;
            }
        }while(wantingtobeclick == 1);
    }

public void actionPerformed(ActionEvent e) {
        if(wantingtobeclick == 1){
            if (e.getSource() == HitMe){
                hitme = 1;
                System.out.println("ICLICKEDHITME");
                g.hitMe(player1);
                waitonbutton();
            }
            if(e.getSource() == Stand){
                hitme = 1;
                g.changestandhit();
            }
        }
    }

It just stays in a infinite loop and doesn't continue on with the loop in main.

The only way I can think to 'pause' a loop is to execute more code during the loop, preferably on a different thread. I.e.

while (true) {
    if (_buttonIsPressed) {
        Thread.sleep(5000); // loop is paused
    }
}

But, more to the point, it feels like you might be going about things the wrong way.

Instead of running a loop to check to see if something has happened, you're better off firing an action once a button is pressed. This is called event-driven programming.

How to pause while loop until a button is pressed, Answer 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� Continue to loop until the user presses a key pressed, at which point the program will pause. If the user presses a key again, then resume the loop. If the user presses a key again, then stop the loop completely (i.e., quit the program). Posted 16-Nov-11 10:58am

I fixed it, just in case anyone else has the same issue:

i added this to main:

        do{

        } while(!(thing.waitonbutton()));

then this to my graphics class:

> public boolean waitonbutton(){
        wantingtobeclick = 1;
        if(hitme == 1){
            wantingtobeclick = 0;
            hitme = 0;
            return true;
        }
        return false;
    }

   public void actionPerformed(ActionEvent e) {
        if(wantingtobeclick == 1){
            if (e.getSource() == HitMe){
                hitme = 1;
                g.hitMe(player1);
            }
            if(e.getSource() == Stand){
                hitme = 1;
                g.changestandhit();
            }
        }
    }

Stop MATLAB execution temporarily - MATLAB pause, pause temporarily stops MATLAB� execution and waits for the user to press any key. The pause function also MATLAB blocks, or hides, the command prompt ( >> ) while it pauses execution. Typing pause(inf) puts you into an infinite loop. Repainting of figure windows, Simulink block diagrams, and Java� windows. 0. The only way I can think to 'pause' a loop is to execute more code during the loop, preferably on a different thread. I.e. while (true) { if (_buttonIsPressed) { Thread.sleep (5000); // loop is paused } } But, more to the point, it feels like you might be going about things the wrong way.

With just an button and a few state variables you will make it with no while loop : i made a little fiddle here : http://jsbin.com/uyetat/2/edit

The code is :

var elapsed=document.getElementById('timeElapsed');
var switcher = document.getElementById('switcher');

var timerStarted    = false;
var refreshInterval = null ;
var timeStarted     = 0    ;

function switchTimer() {
         if (timerStarted) {
              timerStarted = false;
              clearInterval(refreshInterval);
              switcher.value = "start";
         } else {
              timeStarted = Date.now();
              refreshInterval = setInterval (refresh, 100);
              timerStarted=true;
              switcher.value = "stop";
         }    
 }

 function refresh() {
       elapsed.value = (Date.now() - timeStarted);
 }

the html body is :

 <output id='timeElapsed' >not started
 </output>

 <button  onclick='switchTimer()' >
    <output id='switcher' >Start </output>
 </button>

Rq : if you prefer you can use mousedown / mouseup events and measure the hold time.

How to stop a while loop using a GUI pushbutton?, See my attached little demo. It counts when you click the Go button and stops counting when you click the Stop button. If you're talking about blocking a background thread until a button is pressed, pick some object, call wait() on it and then call notify() on it from the event thread when the button is clicked. There are a variety of fancier techniques like blocking queues and mutexes and semaphores in java.util.concurrent if you need something more sophistocated.

I was looking for an answer to the same question recently and as I haven't found any satisfying answer, I was able to handle it like below. Hope this will help anyone for the future running into the same problem. Please note, that I'm a beginner, so there might be a better way to handle it. That said - it does exactly what is expected - stops the loop until button is pressed. In the example below I use for loop, but it works just as well with while.

The trick is to refer to GUI, which is run in a separate thread then backend, and synchronize loop with this thread. Below is of course simplified for the purpose of example. The code displays frame with 1 button, which increases counter every click.

public static void main(String[] args) {

    var button = new JButton("loop");
    button.setPreferredSize(new Dimension(400, 200));

    //create frame thread
    Runnable frameThread = new Runnable() {
        @Override
        public void run() {
            var frame = new JFrame("Wait Example");
            frame.add(button);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        }
    };

    //create action listener for button
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            synchronized (frameThread) {
                frameThread.notifyAll();
            }
        }
    });

    //run frame thread
    EventQueue.invokeLater(frameThread);

    //loop synchronized with frame thread
    for (int i = 1; i < 10; i++) {
        synchronized (frameThread){
            button.setText(Integer.toString(i));
            try {
                frameThread.wait();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
    }

}

How to pause loop to wait for button press, How to pause loop to wait for button press - android. Much better to sit there idle until you need to do something - this is what option 1 achieves. is messed up, I could probably use a temporary fix but I am really just curious why this happens. javascript � android � java � csharp � php � python � ios � jquery � html � sql. Otherwise, the value would never change within the loop, independently of whether the button is pressed or not, so the program would never leave the loop. I´ll set you a challenge. Have a go at making a program that works as a chronometer. Use the LCD and start counting (and displaying) each second that passes until the button is pressed.

How do I pause execution in JavaScript?, A sneaky way to get the effect of a true pause while not burning CPU cycles is to use Client side JavaScript in NN4+ has direct access to Java objects via NN's A way that you can simply test this is to write a very large loop that click on the settings button to customize how the site uses cookies for you. My question is is there a way to start or stop a loop when you press a button. I am now using this to print "hi" to the console if the button has not been pressed, but if the button has been pressed. It will no longer say "hi" in the console. But maybe you guys ( or girls) can help my make the code so when I press the button it stops.

pause Until. Causes your program to wait until an event at a button happens. brick.buttonEnter.pauseUntil(ButtonEvent.Bumped); Parameters. ev: the button action to wait for. The button actions (events) are: click: button was clicked (pressed and released) up: button is released from just being pressed; down: button is just pressed down; Example

As you can see that we have successfully created and added the JButton to the JFrame. Now we want that when we click on the button, some activity should be performed. For this, first of all, we need to implement the ActionListener interface into our class so that we will be able to do some button click event. Implementing ActionListener Interface

Comments
  • What have you tried? Can you show some pieces of code? Why do you want to do that?
  • "loops" are generally only used in realtime games. If using a UI Toolkit, write code that reacts to events (the rules are different for a MVM, but..). That is, do A, wait for the button, do B. (But the title is *very confusing because it's about a button in Java being pressed? How does this Java and Python interact/relate?)
  • React to events. Instead of making the game driven by the loop prompting for input, make the game respond to inputs. If you do want to keep the loop-driven approach, look up "Modal Dialogs".
  • To elaborate on user224's comment on loops, your GUI framework already has a loop for dispatching events(that is how it executes actionPerformed). So you generally wouldn't have your own loop, and instead just have everything be event driven.
  • If you really need to use a loop, you'll probably need to read up on thread management APIs, because you're going to have one thread that your button handlers are on, the GUI's thread, and then your loop on another thread.
  • not having your code event-driven will drain your user's battery in no time. An infinite while loop has the cpu running all the time.