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.
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.
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.