public void keyPressed(KeyEvent e) { char c = e.getKeyChar(); System.out.println("Key pressed: " + c); }
public void keyPressed(KeyEvent e) { char c = e.getKeyChar(); switch(c) { case 'a': // do something when 'a' key is pressed break; case 'b': // do something when 'b' key is pressed break; // add more cases for other keys if needed default: // do something if a key other than 'a' or 'b' is pressed break; } }In this example, the character associated with the key press event is used in a switch statement to perform different actions depending on which key was pressed. The break statement is used to exit the switch statement and prevent the code from executing any unnecessary cases. Overall, the KeyEvent.getKeyChar method is useful in handling key events in Java programs.