Search code examples
javafxwaitinteraction

How to wait for user's action in JavaFX (in the same stage)


Do you know how to wait for the user's input in a for loop? I don't mean the showAndWait() method, because I am not opening a new dialogue stage for the user. So for example, each round of the for loop should be waiting for the user to push a button before going ahead with the next round.

How is it possible? Many thanks!

UPDATE:

Now it came to my mind, that it would work with a while(buttonNotPressed){} but is it a good solution? I mean the while loop is running in this case as crazy until the user won't push the button. Or doest it work somehow similarly with wait methods?

Imagine it as a session: User starts session with handleStart() You give the user 5 questions, one after one. In every iteration, the user can answer the upcoming question and he can save or submit the answer by handleSaveButton() You process the answer as you want, and go ahead with the next iteration. The point is, that the iteration must stop, until the save button hasn't been pressed.


Solution

  • Don't do it like that. The FX toolkit, like any event-driven GUI toolkit, already implements a loop for the purposes of rendering the scene graph and processing user input each iteration.

    Just register a listener with the button, and do whatever you need to do when the button is pressed:

    button.setOnAction(event -> {
        // your code here...
    });
    

    If you want the action to change, just change the state of some variable each time the action is performed:

    private int round = 0 ;
    
    // ...
    
    button.setOnAction(event -> {
        if (round < 5) {
            System.out.println("Round "+round);
            System.out.println("User's input: "+textArea.getText());
            round++ ;
        }
    });