Java - Waiting for some type of key press to continue

CodeGuy picture CodeGuy · Aug 16, 2011 · Viewed 8.7k times · Source

What is the best way to implement a "press x to continue" type of thing in Java?

Specifically, I have a custom class which extends JFrame and a custom class which extends JPanel. I have a Main.java (which has an instance of my JFrame class), and there is a point where I do not want to continue until the user has pressed the space bar:

Main.java:

...code...
frame.waitForSpace();
...more code which gets executed only after space is pressed...

So, in my frame class, how should I implement this:

MyFrame.java:

/* This method only finishes when the space bar is pressed */
public void waitForSpace() {

}

By the way, I have the KeyListener on my JFrame which works when the space button is pressed. But I'm not quite sure how to incorporate that into what I'm trying to do.

Example code would be awesome!

Answer

Ernest Friedman-Hill picture Ernest Friedman-Hill · Aug 16, 2011

Put whatever you want to do when the user presses space into that handler. Most likely you don't want to do (whatever) every time the space bar is pressed, but only some of the time; therefore the event handler should be contingent on the value of some variable, and the code that runs before you want the user to press space should set that variable to the value that means "do it." The handler should set the variable back to the the default value after it runs.