So, I was just wondering. Say I had a simple game of pong consisting of two JButtons as pongs that move with key input, a smaller JButton for the ball moving in a timer and a text box for a score. When I made this, I had to click on the button before I could move it. Is there a way to make it so that the button is selected by default when the program runs so that I can just press keys to move it straight away without clicking it first? Thanks.
Asked
Active
Viewed 4,942 times
1
-
Adjust your logic so that the code inside the JButton is executed within normal program flow. – BlackBox Apr 08 '13 at 13:25
-
1yes is possible with KeyBindings (pong game) and UP and DOWN keys from keyboard, then there no required any focus only correctly to set InputMap, ActionMap to the desired container (to avoiding concurency for another focusable JComponents, sure in the case that they are ....) – mKorbel Apr 08 '13 at 13:37
3 Answers
3
Use the setDefaultButton
method of the JFrame
's root pane:
myFrame.getRootPane().setDefaultButton(button);

Jakub Zaverka
- 8,816
- 3
- 32
- 48
0
In frames constructor
use below code after making button:
this.getRootPane().setDefaultButton(button);

Behzad
- 3,502
- 4
- 36
- 63
-1
I think you can select one by default with requestFocus(). Something like:
defaultJButton.requestFocus();
You should do that at the initialization or every time you want to restart, reset the state or similar.

Filipe Fedalto
- 2,540
- 1
- 18
- 21
-
-1, don't use requestFocus(). Read the API documentation for that method. It will suggest the proper method to use. – camickr Apr 08 '13 at 15:15