我正在尝试制作一款可以四处走动的游戏,而我已经为此发布了一个问题,here。然后有人告诉我tru KeyBindings,我设法创建了这个小型Keyboard类,以获取有关键的常规信息,但我仍然遇到与以前相同的问题:它仅在几秒钟内有效,然后才停止工作,而不会引发任何异常。
代码如下:
public class Keyboard {
private static final HashMap<Integer, Boolean> keys = new HashMap<Integer, Boolean>();
private static final int[] alphabet = new int[] {KeyEvent.VK_W, KeyEvent.VK_A, KeyEvent.VK_S, KeyEvent.VK_D, KeyEvent.VK_P};
@SuppressWarnings("serial")
public static void start(JPanel component) {
for(int c : alphabet) {
keys.put(KeyStroke.getKeyStroke(c, 0, false).getKeyCode(), false);
component.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(c, 0, false), c);
component.getActionMap().put(c, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Pressed:" + c);
keys.put(c, true);
}
});
component.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(c, 0, true), -c);
component.getActionMap().put(-c, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Released:" + c);
keys.put(c, false);
}
});
}
}
public static boolean isPressed(int key) {
return keys.get(key);
}
}
感谢您的帮助!