Java KeyListener - How to detect if any key is pressed?

Efe Esenwa picture Efe Esenwa · Feb 19, 2014 · Viewed 16.3k times · Source

I've added a KeyListener to a TextArea and wish to check if any key is pressed down. I have the following but it's too clumsy to check for all the letters and numbers:

public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_B || 
e.getKeyCode() == KeyEvent.VK_C ||e.getKeyCode() == KeyEvent.VK_D etc...){  

    }   
}

Answer

Embattled Swag picture Embattled Swag · Feb 19, 2014

You wouldn't need any if statements. The keyPressed method is fired whenever a key is pressed, so you're automatically thrown into the method.