这是键盘限制问题吗?
我遇到了一些我正在玩的代码问题。想象一下自上而下的太空射击游戏。我遇到的问题是,在我的电脑上,当我按住向上和向左箭头时,我无法拍摄(空格键)。任何其他方向(向上,向下,向左,向右,向上+向右,向右+向下,向左+向下)都有效。我有一个朋友在他的计算机上运行代码,他发现所有方向都有效,除了向上+向右和向右+向下,但向上+左边工作正常。我们都看了代码,无法搞清楚。这可能是硬件问题吗?
基本上,这就是我正在做的事情:
import javax.swing.*;
import java.awt.event.*;
public class Test extends JFrame
{
boolean up, down, left, right, fire;
// Main constructor
public Test()
{
// listeners for user input
this.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_UP:
{
up = true;
break;
}
case KeyEvent.VK_LEFT:
{
left = true;
break;
}
case KeyEvent.VK_RIGHT:
{
right = true;
break;
}
case KeyEvent.VK_DOWN:
{
down = true;
break;
}
case KeyEvent.VK_SPACE:
{
fire = true;
break;
}
case KeyEvent.VK_ESCAPE:
{
// Exit
System.exit(0);
}
}
}
public void keyReleased(KeyEvent e)
{
// Upon releasing key, stop direction
switch(e.getKeyCode())
{
case KeyEvent.VK_UP:
{
up = false;
break;
}
case KeyEvent.VK_LEFT:
{
left = false;
break;
}
case KeyEvent.VK_RIGHT:
{
right = false;
break;
}
case KeyEvent.VK_DOWN:
{
down = false;
break;
}
}
}
});
}
public static void main(String[] args)
{
// create frame
Test test = new Test();
test.setLocationRelativeTo(null);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
test.loop();
}
public void loop()
{
Timer timer = new Timer(250, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (up)
System.out.println("Moving UP.");
if (left)
System.out.println("Moving LEFT.");
if (right)
System.out.println("Moving RIGHT.");
if (down)
System.out.println("Moving DOWN.");
if (fire)
{
System.out.println("FIRING.");
fire = false;
}
}
});
timer.start();
}
}
这个问题最初被问到here。