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
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: 20271

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: 10824

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!]
I agree. Here's the link:
subject: Regarding Listener
It's not a secret anymore!