Inside the KeyTyped
method, how do I tell if Backspace or Esc is being pressed?
keyCode for the backspace key, U+0008 BACKSPACE.
If you want to test whether the key that the user pressed is the Shift key, you could say "if (evt. getKeyCode() == KeyEvent. VK_SHIFT)". The key codes for the four arrow keys are KeyEvent.
The KeyTyped() listener method is called when a character is typed, but is not useful for virtual keys (arrow keys, function keys, etc). Modifier key (shift, control, etc) status (up/down) can be tested with method calls in the listener. These methods are called whenever any key is pressed or released.
For example, pressing the Shift key will cause a KEY_PRESSED event with a VK_SHIFT keyCode, while pressing the 'a' key will result in a VK_A keyCode. After the 'a' key is released, a KEY_RELEASED event will be fired with VK_A. Separately, a KEY_TYPED event with a keyChar value of 'A' is generated.
Assuming you have attached the KeyListener properly and have implemented the methods required for that KeyListener, to detect specific key-presses simply add the following code:
public void keyReleased(KeyEvent ke)
{
if(ke.getKeyCode() == KeyEvent.VK_BACK_SPACE)
{
//code to execute if backspace is pressed
}
if(ke.getKeyCode() == KeyEvent.VK_ESCAPE)
{
//code to execute if escape is pressed
}
}
The KeyEvent class javadocs can be found at the following link: KeyEvent javadocs.
There you can find a list of all of the Java virtual keycodes used to detect keyboard input when implementing Java KeyListeners and KeyEvents. More information about KeyListeners can be found here: How to Write a Key Listener. To use the keyTyped method as asked, see gangqinlaohu's answer.
http://www.fileformat.info/info/unicode/char/8/index.htm
When arg0.getKeyChar()
is cast to an int: (int)arg0.getKeyChar()
, The backspace key comes up with the value 8, and the Esc key comes up with the value 27.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With