你好:)我试图找到处理java密钥输入的有效方法。我有这段代码:
public void keyPressed(KeyEvent e) {
if (checkInput) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
arrow[LEFT] = true; // boolean for my key input
checkInput = false;
break;
case KeyEvent.VK_RIGHT:
arrow[RIGHT] = true;
checkInput = false;
break;
}
}
}
然后:
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
arrow[LEFT] = false; // boolean for my key input
checkInput = true;
break;
case KeyEvent.VK_RIGHT:
arrow[RIGHT] = false;
checkInput = true;
break;
}
}
}
我的观点是,当我向左或向右按功能键时,按下将停止检查键输入但是它不起作用...在主类中我有构造函数:
public Game() {
addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
player.keyReleased(e); // function mentioted above are from Player class.
}
public void keyPressed(KeyEvent e) {
player.keyPressed(e);
}
});
setFocusable(true);
}
答案 0 :(得分:0)
如果您需要我的意见,请不要在按下某个键时尝试停止按其他键。这似乎是一个用户指定的任务(按下多个键),除非它对你的游戏有直接的伤害,你应该把所有这些努力都放在一个无理的限制中。
public boolean[] keys = new boolean[200]; //just enough to hold all key codes
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
现在,您可以根据按下的键移动。
while(true) {
if(keys[KeyEvent.VK_RIGHT]) {
//move right
}
}
但是,如果你真的想要这个限制:
public boolean[] keys = new boolean[200]
public boolean acceptEvents = true;
public void keyPressed(KeyEvent e) {
if(acceptEvents) {
keys[e.getKeyCode()] = true;
acceptEvents = false;
}
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
acceptEvents = true;
}
很难说你用你给我们的有限资源做了什么(你在代码示例中省略了很多东西),所以让我知道这是否有帮助或者不