This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes How to make a jButton respond to Enter key Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "How to make a jButton respond to Enter key" Watch "How to make a jButton respond to Enter key" New topic
Author

How to make a jButton respond to Enter key

Maysam Sorkhabi
Greenhorn

Joined: Jul 13, 2004
Posts: 23
Hi,
I want to how I can make a jButton react to key baord. I've experimented with setting its mneomonic value but every time I have to press Alt + Enter for the key to respond. I want it to respond to Enter only. Here is what I'm doing. I have two jTextArea's and a "copy" button that takes some text from the fist jTextArea and copies it to the second one. This is just and experimental program. Now at first, jButton1.setEnabled(false). As soon as a key is typed the first jTextArea's event listener detects this and sets jButton.setEnabled(true). Now the button is enabled and I want to how I can have it work by pressing the Enter key on my keybaord instead of having to click on it everytime using the mouse.

Thanks so much for you help
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
The way to bind a KeyStroke to a JComponent is with the components InputMap and ActionMap as shown in the java tutorial.

The difficulty with this is that as long as the focus is on/in a JTextField the JTextField will consume the keystroke. The "enter" keystoke, ie, typing "enter", generates an ActionEvent in a JTextField. So one way to work with this might be to set an Action (as shown below) or add an ActionListener to the JTextField to do the copy behavior.

You can still register the "enter" keystroke on the copy button but to use it you must navigate through/past the JTextFields to the button with the tab key and then press the enter key. Seems like more work than the mnemonic option.

[ July 30, 2004: Message edited by: Craig Wood ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to make a jButton respond to Enter key
 
Similar Threads
setting Default Button
Pressing ENTER when Button is selected doesnt fire buttonActionPerformed...
Regarding Listener
SET A BUTTON AS "DEFAULT"
doing same job on two or more events