Java KeyListener - 如何检测是否按下了任何键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21890963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java KeyListener - How to detect if any key is pressed?
提问by Efe Esenwa
I've added a KeyListener to a TextArea and wish to check if anykey is pressed down. I have the following but it's too clumsy to check for all the letters and numbers:
我已将 KeyListener 添加到 TextArea 并希望检查是否按下了任何键。我有以下内容,但检查所有字母和数字太笨拙了:
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...){
}
}
采纳答案by Embattled Swag
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.
你不需要任何 if 语句。keyPressed
每当按下某个键时都会触发该方法,因此您会自动进入该方法。
回答by Vivek Vermani
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())){
}
}
回答by Nithin CV
I think you can use KeyEvent.getKeyChar() or KeyEvent.getKeyCode()
method which will returns character value/code of key pressed.
我认为您可以使用KeyEvent.getKeyChar() or KeyEvent.getKeyCode()
返回字符值/按键代码的方法。
For alphanumericals A-Z,a-z,0-9;
对于字母数字 AZ,az,0-9;
int key= KeyEvent.getKeyCode();
if((((key>=65)&&(key<=90))||((key>=97)&&(key<=122))||((key>=48)&&(key<=57)))
{
//Do action
}