JTextField textField = new JTextField(); textField.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { e.consume(); // do something with the enter key } } });
public class MyKeyListener extends KeyAdapter { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE) { e.consume(); // do something with the space key } } } JButton button = new JButton("Click me"); button.addKeyListener(new MyKeyListener());In this example, a custom KeyListener is created and added to a JButton. When the user presses the Space key, the event is consumed and a specific action is taken. The KeyEvent class and the consume() method are part of the java.awt.event package.