aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Regarding Action and KeyEvents 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 Action and KeyEvents" Watch "Regarding Action and KeyEvents" New topic
Author

Regarding Action and KeyEvents

adeeb alexander
Ranch Hand

Joined: May 29, 2008
Posts: 268
Hi,
Can any body please tell how to add both ActionListener and KeyListener for a same button. I have already added ActionListeners. Please can anybody show me a simple example which implement this both events.
Thanks and Reagards
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
pete stein
Bartender

Joined: Feb 23, 2007
Posts: 1561
Originally posted by adeeb alexander:
Hi,
Can any body please tell how to add both ActionListener and KeyListener for a same button. I have already added ActionListeners. Please can anybody show me a simple example which implement this both events.
Thanks and Reagards


Why would you even want to add a keylistener to a button? You would have to first get the button in focus, then press the key,... it really doesn't make much sense. Please explain the rationale here.

It suggests to me that you really want to use a mnemonic with your button, and that you haven't yet read the Button tutorial in the Sun Swing Tutorials which describes how to do this. If you read the tutorials and the API before asking questions, you may save yourself and us a lot of time.
adeeb alexander
Ranch Hand

Joined: May 29, 2008
Posts: 268
Actually the default key on the panel is space that is when i press the space key the button is pressed i want to change this to enter key. How?
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
There are two ways you could try:
1 — Make the button the default button for the JRootPane. See the setDefaultButton method in the JRootPane api - the Method Detail entry points to the limitations of this approach. Also, see the second paragraph under the header "How to Use JButton Features" on How to Use Buttons, Check Boxes, and Radio Buttons
2 — You could bind the Enter key to the button. See How to Use Key Bindings for details.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Regarding Action and KeyEvents