1

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
user1366342
  • 63
  • 1
  • 2
  • 7

1 Answers1

2

Two things with this code:

  • I do not see anything about the action map. The input map maps a key to an action identifier, and the action map is the link between the identifier and the actual action. So you normally have code like

    InputMap inputMap = component.getInputMap( );
    ActionMap actionMap =  component.getActionMap();
    Action actionToTrigger = ...;
    actionMap.put( "myAction", actionToTrigger );
    inputMap.put( key, "myAction" );
    
  • If putting your action in the action map with the correct identifier and it still does not work, you might have been using the wrong input map. There are 3 different input maps as explained in the Swing keybindings guide. Try with the others

Perhaps you should consult the Swing keybindings tutorial again as it explains all this in more detail + contains code examples

Robin
  • 36,233
  • 5
  • 47
  • 99