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

青春壹個敷衍的年華 提交于 2019-12-08 08:16:00

问题


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...){  

    }   
}

回答1:


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.




回答2:


I think you can use KeyEvent.getKeyChar() or KeyEvent.getKeyCode() method which will returns character value/code of key pressed.

For alphanumericals A-Z,a-z,0-9;

int key= KeyEvent.getKeyCode();

if((((key>=65)&&(key<=90))||((key>=97)&&(key<=122))||((key>=48)&&(key<=57)))
{
//Do action
}



回答3:


Create a list of respective key events and check if the list contains those events.

List keyEvents = new ArrayList<KeyEvent>();
keyEvents.add(KeyEvent.VK_A);
keyEvents.add(KeyEvent.VK_B);
keyEvents.add(KeyEvent.VK_C);
keyEvents.add(KeyEvent.VK_D);

public void keyPressed(KeyEvent e) {
if(keyEvents.contains(e.getKeyCode())){  

    }   
}


来源:https://stackoverflow.com/questions/21890963/java-keylistener-how-to-detect-if-any-key-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!