This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes Regarding Listener Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Regarding Listener" Watch "Regarding Listener" New topic

Regarding Listener

adeeb alexander
Ranch Hand

Joined: May 29, 2008
Posts: 268
i have a JButton i want to add it the enter key listener i.e when i press enter key then it should perform a task.
Please tell me how can i acheive this.
Thanks and Regards.
Rob Spoor

Joined: Oct 27, 2005
Posts: 19649

Unfortunately, JButtons only use space for pressing it with the keyboard. You can add a KeyListener to catch all key events and then trigger a click when the button is Enter:

This will only work if your button has the focus; if it also has to be triggered if other components have the focus you'll need to add the KeyListener to all controls that can catch the event.

How To Ask Questions How To Answer Questions
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167

Originally posted by adeeb alexander:
..i.e when i press enter key then it should perform a task.

In addition to what Rob said, you can make any single button the default button, without explicitly adding any listeners.
You set it by doing the following:

In this scenario, the "myDefaultButton" is clicked even if it does not have focus.

[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
It is sorta covered in the JavaRanch Style Guide.
subject: Regarding Listener
Similar Threads
Acheiving Focus using EnterKey
JTextField and TAB key
JTable problem
JTextField Action on Tab key
Enter key and JTable