• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

How to make a jButton respond to Enter key

Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
Brace yourself while corporate america tries to sell us its things. Some day they will chill and use tiny ads.
the value of filler advertising in 2021
    Bookmark Topic Watch Topic
  • New Topic