0

i get a trouble when i write this code for a jButton to open new jfame and all that is by using the "Enter key" but it didn't work ,this the code i have writen :

 if(evt.getKeyCode()==KeyEvent.VK_ENTER){
         Chooser ch = new Chooser();
           ch.setVisible(true);

    }

So! why? Please help me and thanks.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Ahmed
  • 13
  • 6
  • See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556). BTW - Add an `ActionListener` to a `JButton` and it will typically respond to the enter key. – Andrew Thompson Nov 25 '14 at 00:54

2 Answers2

1

Buttons don't need a KeyListener (and for the most part shouldn't use them), they use an ActionListener to respond to all activation events, including the action key (which isn't always the Enter), mouse clicks, keyboard shortcuts and programmatically triggered events, it's a much more simplified API.

See How to Use Buttons, Check Boxes, and Radio Buttons, How to Write an Action Listeners and How to Use Actions for more details

You can also set a button as the "default" button which can be activated when not focused (so long as the currently focused component doesn't use/consume the Enter key)

See JRootPane#setDefaultButton and How to Use Root Panes for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

Did You remember to add Listener for jButton ? Please give more code in Your example/ Moreover... searching in google could give interesting results: KeyListener in Textfield not firing when press enter

Community
  • 1
  • 1
Mateusz B
  • 19
  • 3
  • With all due respect, the linked answers are erroneous and misleading. the button API uses the `ActionListener` API to provide event notification which takes into consideration the "action" key (which isn't always the [Enter] key), mouse presses, keyboard shortcuts and programmatically triggered events – MadProgrammer Nov 24 '14 at 21:21