如何使用按键绑定而不是按键侦听器
为什么考虑按键绑定?
键绑定比键侦听器具有优势,包括:
实现按键绑定
按键绑定涉及两个对象:InputMap 和 ActionMap。 InputMap 将用户输入与操作名称相关联,而 ActionMap 将操作名称映射到操作。当按下某个键时,InputMap 检索操作名称,ActionMap 执行相应的操作。
此过程如以下代码所示:
myComponent.getInputMap().put("userInput", "myAction"); myComponent.getActionMap().put("myAction", action);
使用 WHEN_IN_FOCUSED_WINDOW
在给定的示例中,InputMap 使用WHEN_IN_FOCUSED_WINDOW,允许在焦点窗口内输入组件。这适用于多个对象需要同时接收输入的场景。
按键绑定示例
问题代码中提供的示例可以修改为使用按键绑定,如下图:
import javax.swing.*; public class MyGame extends JFrame { private static final String MOVE_UP = "move up"; private static final String MOVE_DOWN = "move down"; private static final String FIRE = "move fire"; static JLabel obj1 = new JLabel(); static JLabel obj2 = new JLabel(); public MyGame() { obj1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke("UP"), MOVE_UP); obj1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke("DOWN"), MOVE_DOWN); obj1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke("control CONTROL"), FIRE); obj1.getActionMap().put(MOVE_UP, new MoveAction(1, 1)); obj1.getActionMap().put(MOVE_DOWN, new MoveAction(2, 1)); obj1.getActionMap().put(FIRE, new FireAction(1)); obj2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke("W"), MOVE_UP); obj2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke("S"), MOVE_DOWN); obj2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke("T"), FIRE); obj2.getActionMap().put(MOVE_UP, new MoveAction(1, 2)); obj2.getActionMap().put(MOVE_DOWN, new MoveAction(2, 2)); obj2.getActionMap().put(FIRE, new FireAction(2)); add(obj1); add(obj2); } static void rebindKey(KeyEvent ke, String oldKey) { obj1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .remove(KeyStroke.getKeyStroke(oldKey)); obj1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStrokeForEvent(ke), obj1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .get(KeyStroke.getKeyStroke(oldKey))); } public static void main(String[] args) { new MyGame(); } private class MoveAction extends AbstractAction { int direction; int player; MoveAction(int direction, int player) { this.direction = direction; this.player = player; } @Override public void actionPerformed(ActionEvent e) { // Implement move action for the player. } } private class FireAction extends AbstractAction { int player; FireAction(int player) { this.player = player; } @Override public void actionPerformed(ActionEvent e) { // Implement fire action for the player. } } }
附加功能
按键绑定提供额外功能:
以上是为什么在 Swing 应用程序中使用键绑定而不是键侦听器?的详细内容。更多信息请关注PHP中文网其他相关文章!