[英]Java swing Key Binding for multiple JPanels
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. 我正在用Java开发一个小游戏(rpg),我需要在代表我游戏各个级别的不同面板中用上,下,左,右移动我的角色。
I use KeyListener first and this is working fine for the first panel, but not with the other. 我首先使用KeyListener,这在第一个面板上工作正常,但在其他面板上则不能。
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) : 我尝试使用一种在参数中使用panelNumber进行移动的方法来使其工作:(这仅适用于第一个面板):
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 ? 我在stackoverflow上看到我必须使用键绑定才能做到这一点,但我不太了解它的工作方式。它是否有机会与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. KeyboardAnimation.java
示例说明如何在两个不同的组件上使用键绑定,并使两个组件在按下键的同时进行动画处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.