0

i working on a little game (rpg) in java and i need to move my character with UP, DOWN, LEFT, RIGHT in different panel who represent each level of my game.

I use KeyListener first and this is working fine for the first panel, but not with the other.

I try to make this work with a method who make the movement with panelNumber in argument : (this is working only for the first panel) :

    private void panelSalle2KeyPressed(java.awt.event.KeyEvent evt) {                                       
      int keyCode = evt.getKeyCode();
      deplacementJoueurSalle(keyCode, 2);
    }  

private void characterMove(int keyCode, int panelNumber){
    JLabel panelCharacterSprite= new JLabel();

    switch(panelNumber){
        case 1:
            panelCharacterSprite= characterPanel1;
            break;
        case 2:
            panelCharacterSprite= characterPanel2;
            break;
        case 3:
            panelCharacterSprite= imagePersoSalle3;
            break;
        default:
            imagePerso = null;
            break;
    }
    int x = panelCharacterSprite.getX();
    int y = panelCharacterSprite.getY();

    switch( keyCode ) {
        case KeyEvent.VK_UP:
        if(y-10 >= -3){
            panelCharacterSprite.setLocation(x, y-10);
        }
        break;
        case KeyEvent.VK_DOWN:
        if(y+10 <= 417){
            panelCharacterSprite.setLocation(x, y+10);
        }
        break;
        case KeyEvent.VK_LEFT:
        if(x-10 >= -1){
            panelCharacterSprite.setLocation(x-10, y);
        }
        break;
        case panelCharacterSprite.VK_RIGHT :
        if(x+10 <= 671){
            panelCharacterSprite.setLocation(x+10, y);
        }

I see on stackoverflow that i have to use key binding for make this but i don't really understand how its work.. do it have a chance that i can make work with keylistener ?

Thx

barnab21
  • 81
  • 1
  • 8
  • See [getInputMap](http://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#getInputMap-int-) and [getActionMap](http://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#getActionMap--). – VGR Sep 09 '15 at 13:44
  • how does it work ? i need to do a "WHEN_IN_FOCUSED_WINDOW" ? – barnab21 Sep 09 '15 at 14:20
  • 2
    `I see on stackoverflow that i have to use key binding` yes, because Key Bindings is the better solution. `do it have a chance that i can make work with keylistener ?` no, because only one component can have focus. That is why Key Bindings is always suggested, it is not limited by this restriction. – camickr Sep 09 '15 at 14:38

1 Answers1

1

Check out Motion Using the Keyboard.

The KeyboardAnimation.java example shows how you can use Key Bindings on two different components and have both components do animation at the same time while a key is pressed.

camickr
  • 321,443
  • 19
  • 166
  • 288