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).
source share