KeyEvent event = new KeyEvent(Component1, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, KeyEvent.VK_A, 'a'); if (event.getID() == KeyEvent.KEY_PRESSED) { System.out.println("The key was pressed."); }
public class KeyListenerDemo implements KeyListener { public void keyPressed(KeyEvent event) { System.out.println("Key pressed: " + event.getID()); } public void keyReleased(KeyEvent event) {} public void keyTyped(KeyEvent event) {} }In this example, the KeyListenerDemo class implements the KeyListener interface and overrides the keyPressed() method. When a key is pressed, the ID of the event is printed to the console. The package library for this code is java.awt.event.