People here keep suggesting to me to use Key Bindings in my Java 2D games instead of Key Listener.
So I learned it and I'd like to know wether I understand correctly how to use it.
Let's say I have a game, with two playes, each player can push 5 buttons.
Player 1:
Player 2:
If I want the program to react differently to each one of the different key-presses, than this is what I have to do: (?)
Is this correct? Is it really logical to create 10 new classes only for pushing buttons? I want to know if I understand correctly how to use Key Bindings, so I can start programming with it.
Thanks
"Is this correct? Is it really logical to create 10 new classes only for pushing buttons?"
The answer is YES. You do need to create 10 different instances. It's not difficult. You can either create a helper class or you can just copy and paste something like this
Action leftAction = new AbstractAction(){
public void actionPerformed(ActionEvent e){
// do something when left button pressed;
}
};
InputMap inputMap = panel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = panel.getActionMap();
inputMap.put(KeyStroke.getKeyStroke("LEFT"), "leftAction");
actionMap.put("leftAction", leftAction); <----
For each different action, just copy and paste the Action
code, change the variable, and the action to perform, and input into the InputMap
and the ActionMap
accordingly.
I use both ways for different scenarios. For graphics i prefer the above way. For things like menus, I tend to use a separate class
Take a look at this example