Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assign Enter as the trigger key of all JButtons in my Java application?

I'm writing a Java Swing application using the Metal look-and-feel. Every time there is a JButton in my application the user uses the Tab key to move the focus to the button and then hits the Enter key. Nothing happens! If he hits the Space key the button events are fired. How do I assign the Enter key to trigger the same events as the Space key? Thank you for your help.

like image 256
Alfred B. Thordarson Avatar asked Jan 13 '09 18:01

Alfred B. Thordarson


People also ask

How do I trigger a JButton with a key press?

How to trigger a JButton with a key press? Add an ActionListener to the button. It will fire an event when the button is in focus and the user presses the enter key.


1 Answers

I found the following:

http://tips4java.wordpress.com/2008/10/25/enter-key-and-button/

Where Rob Camick writes that when using JDK5 and later you simply add...

UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);

...to the application to solve the problem. This did the trick for me! And I can't imagine anything simpler. However, when using older versions of Java you will have to do something like Richard and Peter describe in their answers to this question.

like image 108
Alfred B. Thordarson Avatar answered Sep 27 '22 23:09

Alfred B. Thordarson