This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
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.
 
Don't get me started about those stupid light bulbs.
 
subject: Regarding Action and KeyEvents