我想通过某种方法或事件处理程序检查-用户是否已按下CLI应用程序中的键。
类似的东西:
if(isWPressed)
System.out.println("'W' is pressed");
if(isAPressed)
System.out.println("'A' is pressed");
我已经尝试过以下答案:How do I check if the user is pressing a key?
但是它没有用,并且在导入时我注意到它使用了awt,因此在没有窗口可言的CLI中它没有用。我也不能为此使用Scanner
(如此处建议的:Detect a key press in console),就好像用户会按下多个按钮一样-例如w
和a
,我需要知道两个按钮都被按下了。
您需要使用密钥侦听器,它允许获取密钥
Example
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication7;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
*
* @author wilso
*/
public class List implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void keyPressed(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void keyReleased(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
如果您不想使用awt,则可以使用扫描仪或事件
@Override
public void nativeKeyPressed(NativeKeyEvent e) {
String temp = NativeKeyEvent.getKeyText(e.getKeyCode());
if (validHotKeys.contains(temp)) {
if (!pressedHotKeys.contains(temp)) {
pressedHotKeys.add(temp);
System.out.println(pressedHotKeys.toString());
}
}
if (validAlphaKeys.contains(temp)) {
if (!pressedAlphaKeys.contains(temp)) {
pressedAlphaKeys.add(temp);
System.out.println(pressedAlphaKeys.toString());
}
}
}