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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.