Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hotkey/Shortcut for JButton

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"

like image 445
Lord Rixuel Avatar asked Mar 31 '13 00:03

Lord Rixuel


People also ask

What is shortcut key for run in Oracle?

Ctrl+F5. Build and Run. Ctrl+Alt+B. Build Module. Ctrl+F4.


2 Answers

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

like image 97
Héctor van den Boorn Avatar answered Sep 29 '22 11:09

Héctor van den Boorn


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.

like image 44
Hovercraft Full Of Eels Avatar answered Sep 29 '22 10:09

Hovercraft Full Of Eels