0

我正在尝试制作 Snake 游戏。但我无法移动一个矩形框(即蛇)。很抱歉提出这样的问题!但我是java初学者,我不知道我的代码中的问题出在哪里。

    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);
}


}
4

1 回答 1

2

看起来有NullPointerException在计时器动作中。new Snakexx().getGraphics();是获取Graphics实例的不正确方法。当您实际上在计时器的每个滴答声上分配面板的新实例时,问题就更大了。

不要getGraphics()用于您的绘画,因为它是临时缓冲区,会在下次重新绘画时回收。如果需要的paintComponent()话,你会画画吗?repaint()

立即修复将添加repaint()并注释掉绘画代码,即:

public void actionPerformed(ActionEvent e) {
    a += x;
    b += y;
    // Graphics gr;
    // gr= new Snakexx().getGraphics();
    // gr.fillRect(a,b,10,10) ;

    repaint();
}

有关详细信息,请参阅在 AWT 和 Swing中执行自定义绘画和绘画。

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

于 2013-03-06T01:58:44.557 回答