I have the following code of JButton in Java:
enterButton = new JButton("Enter");
enterButton.setMnemonic(KeyEvent.VK_ENTER); // Shortcut: Alt + Enter
The question is simply: Instead of having the shortcut "Alt+Enter", how do I set a shortcut "Enter"?
I simply prefer pressing "Enter" instead of holding "Alt" and pressing "Enter"
Ctrl+F5. Build and Run. Ctrl+Alt+B. Build Module. Ctrl+F4.
I had the same issue: I have a form an whenever I am edditing a field I want to press enter for it to fire the actionPerformed event.
I fixed it with this:
The JPanel
the button and the rest of the form is located on is called content
:
content.getRootPane().setDefaultButton(enterButton);
This keeps the button always selected so when you press enter, its corresponding actionPerformed event fires (remember to add an ActionListener to it!)
Hope this helps you!
Kind regards,
Héctor
You can make a button respond to the Enter keyword, via a special technique, one that only works for the Enter key, and to do this you want to get the JRootPane of the top level window that displays the button and call setDefaultButton(myButton)
on this root pane.
i.e.,
enterButton = new JButton("Enter")
// after the enterButton has been added to the GUI and the GUI displayed, call:
JRootPane rootPane = SwingUtilities.getRootPane(enterButton);
rootPane.setDefaultButton(enterButton);
Otherwise for non-enter keys, you'd need to use Key Bindings which is do-able, but would require a bit more effort.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With