好的,首先。 如果我做 System.out.println(e); 当我按下键时确实会打印出来。但是我一辈子都想不出如何将它存储到一个 int 中。如果我这样做,我的 IDE 不会给我任何错误 int pressed = e.KEY_PRESSED();或 int pressed = e.getKeyCode(); 但是如果我尝试打印 pressed 则什么也不会发生。
几个小时以来,我一直在努力让它工作,谷歌搜索 KeyEvent 处理程序和 Javadoc 似乎对我帮助不大。
public void keyPressed(KeyEvent e) {
pressed = e.getKeyCode();
System.out.println(pressed);
do{
time = System.currentTimeMillis();
do{
if(pressed == 37||pressed==38||pressed==39||pressed==40){
lastvalid=pressed;
}
}
while(System.currentTimeMillis() < time + speed);
switch(lastvalid){
case 37: catarloc.set(0, (Integer)catarloc.get(0)-1); break;
case 38: catarloc.set(1, (Integer)catarloc.get(1)-1); break;
case 39: catarloc.set(0, (Integer)catarloc.get(0)+1); break;
case 40: catarloc.set(1, (Integer)catarloc.get(1)+1); break;
}
if(Math.random() > .95 || apples < 1){
applearray[(int)(Math.random()*100/2.8)][(int)(Math.random()*100/4)] = true;
apples++;
}
score+=catarloc.size()-1;
label.setText("Score "+ score);
mainWindow.repaint();
}
while(win == false || lose == false);
最佳答案
keyEvent.getKeyCode()
呢? ?它返回一个整数。 KEY_PRESSED
是 KeyEvent 上的静态最终 int 成员,表示按下键时的事件,而不是实际的键代码。
更新:(糟糕)我看到您已经尝试过 getKeyCode。如果你打印 getKeyLocation
会发生什么或 getKeyChar
?
关于java - 我无法让 KeyEvent 监听器工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3873469/