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