Java Swing 中的鍵綁定與鍵偵聽器:綜合指南
鍵綁定和鍵偵聽器是處理用戶輸入事件的兩種方法來自Java Swing 應用程式中的按鍵。雖然按鍵偵聽器提供了一種簡單的方法來檢測按鍵,但按鍵綁定具有多個優點,包括:
理解鍵綁定
按鍵綁定涉及兩個物件:
實作鍵綁定
要建立單一鍵綁定,請使用下列結構:myComponent.getInputMap().put("userInput", "myAction"); myComponent.getActionMap().put("myAction", action);
使用 WHEN_IN_FOCED_WINDOW InputMap
WHEN_IN_FOCUSED_WINDOW 的 InputMap 允許聚焦視窗中的多個元件同時接收輸入。例如,如果聚焦視窗中有多個坦克並希望它們接收輸入,請使用以下結構:tank1.getInputMap(IFW).put(KeyStroke.getKeyStroke("W"), "move up"); tank2.getInputMap(IFW).put(KeyStroke.getKeyStroke("S"), "move down"); // ... tankN.getInputMap(IFW).put(KeyStroke.getKeyStroke("T"), "fire");
重新綁定鍵
重新綁定使用KeyListener進行鍵:obj1.getInputMap(IFW).remove(KeyStroke.getKeyStroke(oldKey)); // ... obj1.getInputMap(IFW).put(KeyStroke.getKeyStrokeForEvent(ke), obj1.getInputMap(IFW).get(KeyStroke.getKeyStroke(oldKey)));
程式碼範例
以下是示範鍵綁定的程式碼範例:import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyGame extends JFrame { public MyGame() { // Do layout management, create objects, etc. JLabel obj1 = new JLabel(); JLabel obj2 = new JLabel(); // Set key bindings for object 1 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)); // Set key bindings for object 2 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 objects to the JFrame add(obj1); add(obj2); } // Handle key rebinding public static void rebindKey(KeyEvent ke, String oldKey) { // Find and replace key binding } // Main method public static void main(String[] args) { new MyGame(); } // Inner class for move action 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 logic } } // Inner class for fire action private class FireAction extends AbstractAction { int player; FireAction(int player) { this.player = player; } @Override public void actionPerformed(ActionEvent e) { // Implement fire logic } } }
結論
鍵綁定提供了一種強大而靈活的方式處理Java Swing應用程式中的使用者輸入事件。透過利用按鍵綁定,開發人員可以增強應用程式的回應能力、可維護性和可重複使用性。以上是Java Swing 鍵處理:鍵綁定或鍵偵聽器 – 您應該選擇哪一個?的詳細內容。更多資訊請關注PHP中文網其他相關文章!