• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding Listener

 
adeeb alexander
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Maneesh Godbole
Saloon Keeper
Posts: 11096
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic