KeyListener无法正常工作 [英] KeyListener is not working

查看:73
本文介绍了KeyListener无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码不起作用.我正在尝试使用按键方法向左,向右,向上和向下移动播放器,但是当我按按键时它没有响应.我并没有将整个代码粘贴到移动框的那部分,还有其他if语句来实现其他内容的移动.

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.

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因无法正常运行而臭名昭著(实际上,它们确实可以正常工作,只是不是您认为的那样).

KeyListeners are notorious for not working (well actually they do, just not the way you think they should).

KeyListener的问题在于,它们只会在注册其组件的组件具有焦点并具有焦点(也称为键盘焦点)时才会做出反应.

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).

相反,应在允许的范围内使用键绑定确定触发它们的焦点状态.

Instead, you should use Key Bindings as they allow to determine the focus state under which they are triggered.

这篇关于KeyListener无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆