Key press

I want to add a KeyEventListener to a JButton that responds to an Enter key using the following code segment:

private void jButton3KeyPressed(java.awt.event.KeyEvent evt) { if (evt.getKeyCode() == 10) { eventRegister(); } } 

I pressed the space bar instead of input, and the if condition is set to true and called eventRegister . What for? How could I prevent this manner?

+4
source share
3 answers
  • do not use KeyListener or MouseListener for JButton or JButtons JComponent , these events are implemented in API or ButtonsModel , each of them can be testable, with consume() of KeyEvent

  • JButton implemented the ENTER and SPACE key as an accelerator in KeyBindings

  • remove SPACE from KeyBindings , but don’t assume that I wouldn’t confuse users, of course depends on

+6
source

Instead KeyListeners should use KeyBinding .


But even if you do not, your current code should work, as in this example.

 JFrame frame = new JFrame(); frame.setLayout(new FlowLayout()); JButton button=new JButton("do something"); button.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent evt) { if (evt.getKeyCode() == 10) { System.out.println("it is ten"); } } }); frame.getContentPane().add(button); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); frame.setVisible(true); 

Unless you publish a complete (but short) example that you can use to reproduce your problem, it is almost impossible to say what you did wrong.

(I will try to edit this answer if you add additional information about your code).

+1
source

try using

 if (evt.getKeyCode() == KeyEvent.VK_ENTER) { .... 

Events with keystrokes and keystrokes are lower and depend on the platform and keyboard layout.

Since java is a cross platform, do not use hardcoded values ​​for keyboard codes.

0
source

Source: https://habr.com/ru/post/1490030/


All Articles