首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java - KeyListener事件不触发

Java - KeyListener事件不触发
EN

Stack Overflow用户
提问于 2012-04-16 03:18:19
回答 2查看 1K关注 0票数 1

我已经开始用java写一个简单的平台游戏。作为测试,我编写了这个简单的程序,当您按下箭头键时,它会在applet周围移动一个矩形。关键事件根本没有触发。代码如下:

代码语言:javascript
复制
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends Applet implements Runnable, KeyListener
{
  //setup data
  Thread t;
  Image buffimg;
  Graphics draw;
  Dimension dim;

  //game variables
  int charx = 400;//rectangles X and Y positions
  int chary = 50;
  boolean leftArrow = false;
  public void init()
  {
        setSize(800, 500);
        t = new Thread(this);
        t.start();
       addKeyListener( this );
  }
  public void run()
  {
        while(true)
        {
          repaint();
          moveChar();//move the rectangle
          try {
                t.sleep(1000/30);
          } catch (InterruptedException e) { ; }
        }
  }
   public void keyPressed( KeyEvent e ) 
   { 
       int k = e.getKeyCode();
       if(k == 37)
       {
           leftArrow = true;
           charx--;
       }

   }
   public void keyReleased( KeyEvent e ) 
   { 
       if(e.getKeyCode() == 37)
       {
           leftArrow = false;
       }
   }
   public void keyTyped( KeyEvent e ) 
   {
   }
  public void moveChar()
  {
      //move rectangle on left arrow key press
      if(leftArrow == true)
      {
          charx--;
      }  
  }
  public void paint(Graphics g)
  {
      g.drawRect(charx, chary, 100, 100);
  }
  public void update (Graphics g)
  {
      //double buffering

      // initialize buffer
      if (buffimg == null)
      {
          buffimg = createImage (this.getSize().width, this.getSize().height);
          draw = buffimg.getGraphics ();
      }
      // clear screen in background
      draw.setColor (getBackground ());
      draw.fillRect (0, 0, this.getSize().width, this.getSize().height);
      // draw elements in background
      draw.setColor (getForeground());
      paint (draw);
      // draw image on the screen
      g.drawImage (buffimg, 0, 0, this);
  } 
}

为什么他们不开火,我该如何解决这个问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-16 03:33:10

代码语言:javascript
复制
this.requestFocusInWindow(); // end of init(), or better, in start()
票数 4
EN

Stack Overflow用户

发布于 2012-04-16 03:43:25

我试过你的代码了。它按其应有的方式工作。

问题是,您需要先在绘图区域上按下鼠标以使其成为焦点,然后它才能接收事件。

要自动执行此操作,请使用以下命令: requestFocusInWindow()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10165201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档