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!
Using a CountDownLatch when await() is invoked, the current main() thread will wait until the countDown() method is called from another thread.
The KeyEventDispatcher lets you add a keystroke listener globally. So whenever a key is pressed dispatchKeyEvent() gets called from the EDT (Event Dispatching Thread) and there you can check for ‘space’ being pressed and release the countdown latch that main() is waiting on.
However, if the thread that calls waitForSpace() is the EDT, then you will be forcing the EDT to wait for itself, causing deadlock. It is impossible to wait on the EDT and still receive key events as far as I know.
This will work so long as a JFrame has focus: