Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java KeyListener: KeyTyped Backspace, Esc as input

Inside the KeyTyped method, how do I tell if Backspace or Esc is being pressed?

like image 250
Justin Avatar asked Mar 28 '13 23:03

Justin


People also ask

What is the keyCode for backspace Java?

keyCode for the backspace key, U+0008 BACKSPACE.

How do you check if a key is being pressed in Java?

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.

What does keyTyped do in Java?

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.

How do you use key events in Java?

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.


2 Answers

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.

like image 87
BMFredrick Avatar answered Oct 14 '22 16:10

BMFredrick


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.

like image 30
Justin Avatar answered Oct 14 '22 15:10

Justin