简体   繁体   English

KeyListener无法运作

[英]KeyListener is not working

The following code is not working. 以下代码不起作用。 I am trying to move a player left, right, up, and, down using key pressed method but when i press the keys it does not respond. 我正在尝试使用按键方法向左,向右,向上和向下移动播放器,但是当我按按键时它没有响应。 I did not paste the whole code just the part that moves the box there are other if statements to achieve movement of other contents. 我并没有将整个代码粘贴到移动框的那一部分,还有其他if语句来实现其他内容的移动。


public class innerClassKeyPressed {


   void  keyPressed( KeyEvent e)
   {
    int key= e.getKeyCode();
    if(key==KeyEvent.VK_LEFT){
        dx=-1;
    }
     if(key==KeyEvent.VK_RIGHT){

         dx=1;
    }
    if (key==KeyEvent.VK_UP){
        dy=-1;
    }
     if (key==KeyEvent.VK_DOWN){
        dy=1;
     }
      if (key == 82)
     {
          initLevel(currlevel);

     } //R
     if (key == 78)
     {
         currlevel++;
          initLevel(currlevel);
      } 

      if ( (key == KeyEvent.VK_LEFT ) && ( key  == KeyEvent.VK_RIGHT ) && 
      (key == KeyEvent.VK_UP ) && ( key == KeyEvent.VK_DOWN )) { 

         return;
       }


        for (int row=0; row < myArray.length; row++)

        {
            for (int column=0; column < myArray[row].length; column++)
            {
                 if( myArray[row][column]==  Contents.PLAYER)                       { 
                        if (myArray[row+dy][column+dx] == Contents.BOX)
                        {

                            if (myArray[row+dy*2][column+dx*2] == Contents.EMPTY)

                             {

                                myArray[row+dy][column+dx]= Contents.PLAYER; 
                                 myArray[row][column]= Contents.EMPTY;

                                myArray[row+dy*2][column+dx*2]= Contents.BOX;

KeyListeners are notorious for not working (well actually they do, just not the way you think they should). KeyListeners器因无法正常运行而臭名昭著(实际上,它们确实在工作,只是不是您认为的那样)。

The problem with KeyListener is that they will only react when the component they are registered to is focusable and has focus (also known as key board focus). KeyListener的问题在于,它们只会在注册其组件的组件具有焦点并具有焦点(也称为键盘焦点)时作出反应。

Instead, you should use Key Bindings as they allow to determine the focus state under which they are triggered. 而是应使用按键绑定,因为它们允许确定触发它们的焦点状态。

As I'm guessing your using a JFrame and Canvas to draw your player then I'm also going to presume this isnt working because you have not added the KeyListener to the JFrame. 当我猜测您使用JFrame和Canvas绘制播放器时,我还假定这没有用,因为您尚未将KeyListener添加到JFrame中。

For example: 例如:

JFrame frame = new JFrame();
frame.addKeyListener(keylistener);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM