1

小型单窗口应用程序(游戏)具有由 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)?它会在程序运行时即时更改绑定吗?

4

1 回答 1

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");
于 2012-12-15T14:39:18.437 回答