首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >KeyListener不工作了吗?

KeyListener不工作了吗?
EN

Stack Overflow用户
提问于 2013-03-06 09:45:28
回答 1查看 98关注 0票数 0

我在试着做蛇的游戏。但是我不能移动一个长方形的盒子(这是蛇)。很抱歉问了这样一个问题!但是我是一个java的初学者,我不知道我的代码中的问题在哪里。

代码语言:javascript
复制
    class Snakexx extends JPanel implements ActionListener , KeyListener{
public static int a,b,x,y;
public int fooda,foodb;
Random rnd ;
Timer t = new Timer(1,this);
public void keyPressed(KeyEvent e){
         if(e.getKeyCode()==e.VK_UP)
        {
        x=0;
        y=-1;
        }
        if(e.getKeyCode()==e.VK_LEFT)
        {
        x=-1;
        y=0;            
        }
        if(e.getKeyCode()==e.VK_DOWN)
        {
        x=0;
        y=1;
        }
        if(e.getKeyCode()==e.VK_RIGHT)
         {
            x=1;
            y=0;
            }
        }
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent f){}

protected Snakexx(){
rnd = new Random();
fooda=rnd.nextInt(1300);
foodb=rnd.nextInt(300);
a=20;
b=20;
t.start();
addKeyListener(this);
setFocusable(true);

} 



protected void paintComponent(Graphics g) {

super.paintComponent(g);
g.fillRect(a,b,10,10) ;
g.fillRect(fooda,foodb,10,10) ;
}
public void actionPerformed(ActionEvent e){
a+=x;
b+=y;
Graphics gr;
gr= new Snakexx().getGraphics();
gr.fillRect(a,b,10,10) ;

}
}

 public class Snake2{


 public static void main(String args[]) 
{
Snakexx abcd = new Snakexx();
JFrame jfrm = new JFrame("Snake Game");
jfrm.setSize(1300, 650);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrm.setVisible(true);

jfrm.add(abcd);
}


}
EN

Stack Overflow用户

发布于 2013-03-06 09:58:45

看起来在计时器操作中有NullPointerExceptionnew Snakexx().getGraphics();是获取Graphics实例的错误方式。这甚至更有问题,因为您实际上是在为计时器的每一个滴答器分配面板的新实例。

不要为你的绘画使用getGraphics(),因为它是临时缓冲区,会在下一次重新绘制时回收。如果需要,您是否在paintComponent()中进行绘制并调用repaint()

直接的解决办法是添加repaint()并注释掉绘制代码,即:

代码语言:javascript
复制
public void actionPerformed(ActionEvent e) {
    a += x;
    b += y;
    // Graphics gr;
    // gr= new Snakexx().getGraphics();
    // gr.fillRect(a,b,10,10) ;

    repaint();
}

有关详细信息,请参阅Performing Custom PaintingPainting in AWT and Swing

此外,按键侦听器是键盘输入的低级接口。确保面板是可聚焦的,并且具有焦点。聚焦可能是非常棘手的。使用键绑定要好得多,有关详细信息,请参阅How to Use Key Bindings

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

https://stackoverflow.com/questions/15237501

复制
相关文章

相似问题

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