2013-03-06 86 views
0

我试图让蛇游戏。但我无法移动一个矩形框(这是Snake)。 对不起,提出这样的问题!但我是一个在java中的初学者,我不知道我的代码中的问题在哪里。KeyListener无法正常工作?

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


} 
+3

对代码块使用一致的逻辑缩进。代码的缩进旨在帮助人们理解程序流程。 – 2013-03-06 02:20:36

回答

2

看起来像在计时器动作中有NullPointerExceptionnew 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(); 
} 

有关更多信息,请参见Performing Custom PaintingPainting in AWT and Swing

另外,按键监听器是键盘输入的低级接口。确保面板可以调焦并且有焦点。聚焦可能非常棘手。使用Key Bindings更好,详情请参见How to Use Key Bindings