How to associate pressing "enter" with clicking button?

Connor picture Connor · Jan 16, 2011 · Viewed 18.5k times · Source

In my swing program I have a JTextField and a JButton. I would like for, once the user presses the "enter" key, the actionListener of the JButton runs. How would I do this? Thanks in advance.

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Jan 16, 2011

JRootPane has a method setDefaultButton(JButton button) that will do what you want. If your app is a JFrame, it implements the RootPaneContainer interface, and you can get the root pane by calling getRootPane() on the JFrame, and then call setDefaultButton on the root pane that was returned. The same technique works for JApplet, JDialog or any other class that implements RootPaneContainer.