I am trying to create a Tanks game but am still learning how to do graphics programming in Java. I had initially tried moving one of two images (which one depends on which player is going) with KeyListeners. I was told that Key Bindings might be a more effective way of going about this. Here is some of my code:
public class FrameMain extends JFrame{
...
public FrameMain(){
this.addBindings();
The addBindings() method:
protected void addBindings() {
InputMap inputMap = pnlPlay.getInputMap();
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Event.KEY_PRESS);
inputMap.put(key, pnlPlay.pnlGame.MoveTank(2, pnlPlay.nPlayer));
key = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Event.KEY_PRESS);
inputMap.put(key, pnlPlay.pnlGame.MoveTank(-2, pnlPlay.nPlayer));
}
The MoveTank method:
public int MoveTank(int xChange, int nPlayer){
System.out.println("move "+nPlayer);
if(nPlayer==0){
tank1.x+=xChange;
}else tank2.x+=xChange;
repaint();
return 1;
}
The problem I'm having is that, when I press either the right or left arrow key, I am not getting any kind of response. It should be printing "move #" but it's not. If anyone knows what I have done wrong or could point me in the direction of some code that does the same thing I would appreciate it. I learn best from seeing the code in working order and then playing around with it.