【问题标题】:Switching set of keyboard shortcuts at run-time在运行时切换一组键盘快捷键
【发布时间】:2012-12-02 22:29:03
【问题描述】:

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

【问题讨论】:

  • 是什么阻止您启用这两种变体并让用户选择?
  • @AlexStybaev,这对你来说可能听起来很明显,但我对 GUI 不熟悉,问题是“如何?”。
  • 好吧,现在我们已经到了您应该发布一些代码或至少提供有关您面临的问题的更多信息的地步。
  • 您是在问如何更改键映射,如何构建让用户选择键映射的用户界面,还是两者兼而有之?
  • 引用了一个例子here

标签: java swing keyboard-shortcuts key-bindings


【解决方案1】:

我倾向于使用 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");

【讨论】:

  • +1 - 除了 WHEN_IN_FOCUSED_WINDOW 的轻微挑剔:那些在链中最后被提供,只有在没有其他人声称它们的情况下。通常情况下,您会更喜欢 WHEN_ANCESTOR。
猜你喜欢
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多