我在试着做蛇的游戏。但是我不能移动一个长方形的盒子(这是蛇)。很抱歉问了这样一个问题!但是我是一个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);
}
}发布于 2013-03-06 09:58:45
看起来在计时器操作中有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();
}有关详细信息,请参阅Performing Custom Painting和Painting in AWT and Swing。
此外,按键侦听器是键盘输入的低级接口。确保面板是可聚焦的,并且具有焦点。聚焦可能是非常棘手的。使用键绑定要好得多,有关详细信息,请参阅How to Use Key Bindings。
https://stackoverflow.com/questions/15237501
复制相似问题