如何使用按鍵綁定而不是按鍵偵聽器
為什麼要考慮按鍵綁定?
鍵綁定比鍵偵聽器具有優勢,包括:
實現按鍵綁定定
按鍵綁定涉及兩個物件:InputMap 和ActionMap。 InputMap 將使用者輸入與操作名稱相關聯,而 ActionMap 將操作名稱對應到操作。按下某個按鍵時,InputMap 會擷取動作名稱,ActionMap 執行對應的動作。
此流程如以下程式碼所示:
myComponent.getInputMap().put("userInput", "myAction"); myComponent.getActionMap().put("myAction", action);
使用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中文網其他相關文章!