问题
I'm developing the GUI design for my database.
After designing most of the frame and debugging them I released I needed to add the option to 'trigger' buttons using ENTER key, instead of only clicking on it.
How should I go about it? I'm currently using MouseListener for my buttons and want to add a Listener that performs the same actions when ENTER key is pressed. Thank you
回答1:
Using the Enter key to invoke the Action of a button is a LAF issue. This is supported in Windows, but in the default Metal LAF you use the space bar.
Check out Enter Key and Button for a couple of solutions:
You can use the UIManager to make the button the default button as you tab from button to button:
UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);You can use Key Bindings to map the Enter Key pressed/released events.
回答2:
You should never need to use a MouseListener with any kind of button. Instead you should be using an ActionListener. This will alert you when the button is clicked or activated by the keyboard based on the requirements of the look and feel
Take a look at How to Write an Action Listeners and How to Use Buttons, Check Boxes, and Radio Buttons for more details
来源:https://stackoverflow.com/questions/23769423/triggering-jbuttons-via-enter-key