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

Alfred B. Thordarson picture Alfred B. Thordarson · Jan 13, 2009 · Viewed 20.6k times · Source

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.

Answer

Alfred B. Thordarson picture Alfred B. Thordarson · Jan 13, 2009

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.