使用按鍵綁定
為了解決允許兩個玩家使用不同的按鍵控制單獨的球拍的主要問題,建議的解決方案是使用Swing 鍵綁定。這種方法具有以下優點:
程式碼範例
提供的程式碼範例示範如何在Java 應用程式中實作鍵綁定:
//Create a GameKeyBindings object associated with the game panel and the two paddle entities. GameKeyBindings gameKeyBindings = new GameKeyBindings(gp, player1Entity, player2Entity);
在程式中實作鍵綁定:
//Key binding for Player 1's paddle: Up arrow key gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "W pressed"); gp.getActionMap().put("W pressed", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { entity.UP = true; } }); //Key binding for Player 2's paddle: Down arrow key gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down pressed"); gp.getActionMap().put("down pressed", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { entity2.DOWN = true; } }); // Similar key binding definitions for releasing the keys.
在程式中實作鍵綁定:
在程式中實作鍵綁定:在GameKeyBindings 類別中,為每個球拍的移動定義鍵綁定:
Collections.synchronizedSet(new HashSet
以上是Swing 鍵綁定如何讓兩個玩家在 Java 遊戲中使用不同的鍵控制單獨的槳?的詳細內容。更多資訊請關注PHP中文網其他相關文章!