File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Regarding Listener" Watch "Regarding Listener" New topic
Author

Regarding Listener

adeeb alexander
Ranch Hand

Joined: May 29, 2008
Posts: 268
Hi,
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
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 9990
    
    7

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: http://aspose.com/file-tools
 
subject: Regarding Listener
 
Similar Threads
Acheiving Focus using EnterKey
JTextField and TAB key
JTable problem
JTextField Action on Tab key
Enter key and JTable