So what I've been attempting to do is essentially have it set to when the enter key is pressed on my JFrame in java it detects it so I can do an action like start a game by switching to the next screen. So I was wondering if anyone could help me figure out how to do this in particular. Just being able to have something that constantly checks to see if the Enter Key has been pressed on the JFrame
Asked
Active
Viewed 184 times
0
-
1Every JFrame has a JRootPane. You’ll want to call [getActionMap()](http://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#getActionMap--) and [getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)](http://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#getInputMap-int-) on that JRootPane. – VGR Mar 09 '17 at 17:07
-
@VGR would you mind explaining it a bit to me? – J.F78 Mar 09 '17 at 17:29
-
Follow those links and read the documentation for the ActionMap class and the InputMap class. They are pretty short and to the point. Create an Action (usually a subclass of AbstractAction); add it to the JRootPane’s ActionMap with a name of your choosing, usually a String; add a KeyStroke to the JRootPane’s InputMap which maps to that same name. – VGR Mar 09 '17 at 17:32
1 Answers
1
have it set to when the enter key is pressed on my JFrame in java it detects it so I can do an action like start a game by switching to the next screen.
How do people know to use the Enter key?
Typically you would have a button like "Start Game" for the user to click.
You can easily make this the default button by using:
frame.getRootPane().setDefaultButton( startGameButton );
Now the user will be able to either:
- click on the button
- use the Enter key to invoke the button.

camickr
- 321,443
- 19
- 166
- 288