在运行时切换一组键盘快捷键

时间:2012-12-14 21:58:54

标签: java swing keyboard-shortcuts key-bindings

小型单窗口应用程序(游戏)具有由GUI按钮控制的图形对象。我有一组映射到它们的键盘快捷键(即箭头键)。是否可以轻松地选择动态更改快捷方式组合?例如,JOption在箭头键和WASD之间进行选择?

虽然我仍在努力解决绑定问题,但这是我对交换机本身的想法:

// KeyStroke objects to be used when mapping them to the action
KeyStroke keyUp, keyLeft, keyRight, keyDown;

JRadioButton[] kbdOption = new JRadioButton[2];

kbdOption[0] = new JRadioButton("Arrow Keys");
kbdOption[1] = new JRadioButton("WASD");

if (kbdOption[0].isSelected()) {
    keyUp = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
    keyLeft = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
    keyRight = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
    keyDown = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
} else if (kbdOption[0].isSelected()) {
    keyUp = KeyStroke.getKeyStroke(KeyEvent.VK_W, 0);
    keyLeft = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0);
    keyRight = KeyStroke.getKeyStroke(KeyEvent.VK_D, 0);
    keyDown = KeyStroke.getKeyStroke(KeyEvent.VK_S, 0);
}

由于我自己无法测试,它看起来不错吗?范围是否正确(也就是说,我可以在构建GUI其余部分的相同方法中实际使用它,还是应该从其他地方调用if-else)?当程序运行时,它是否可以即时更改绑定?

1 个答案:

答案 0 :(得分:2)

我倾向于选择Alex Stybaev的第一个回复:只需添加所有绑定。像这样:

gamePanel.getActionMap().put("left", leftAction);
gamePanel.getActionMap().put("right", rightAction);
gamePanel.getActionMap().put("up", upAction);
gamePanel.getActionMap().put("down", downAction);

InputMap inputMap =
    gamePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

inputMap.put(KeyStroke.getKeyStroke("LEFT"),  "left");
inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "right");
inputMap.put(KeyStroke.getKeyStroke("UP"),    "up");
inputMap.put(KeyStroke.getKeyStroke("DOWN"),  "down");

inputMap.put(KeyStroke.getKeyStroke("A"), "left");
inputMap.put(KeyStroke.getKeyStroke("D"), "right");
inputMap.put(KeyStroke.getKeyStroke("W"), "up");
inputMap.put(KeyStroke.getKeyStroke("S"), "down");

inputMap.put(KeyStroke.getKeyStroke("KP_LEFT"),  "left");
inputMap.put(KeyStroke.getKeyStroke("KP_RIGHT"), "right");
inputMap.put(KeyStroke.getKeyStroke("KP_UP"),    "up");
inputMap.put(KeyStroke.getKeyStroke("KP_DOWN"),  "down");

inputMap.put(KeyStroke.getKeyStroke("NUMPAD4"), "left");
inputMap.put(KeyStroke.getKeyStroke("NUMPAD6"), "right");
inputMap.put(KeyStroke.getKeyStroke("NUMPAD8"), "up");
inputMap.put(KeyStroke.getKeyStroke("NUMPAD2"), "down");