为什么会有运行错误
import java.awt.*;import java.awt.geom.*;
import java.util.*;
import java.awt.event.*;
import java.math.*;
import javax.swing.*;
class Snake extends JPanel implements KeyListener
{
Vector<Rectangle2D.Float> snakelength=new Vector<Rectangle2D.Float>();
private float x=210,y=220;
private String direction="left";
private boolean foodshow=true;
private Rectangle2D.Float lastsnakeElement;
private boolean firststart=true;
private Rectangle2D.Float food;
private Rectangle2D.Float firstsnakeElement=new Rectangle2D.Float(x,y,10,10);
private boolean eatfood=false;
Snake()
{
for(int i=0;i<5;i++)
{
snakelength.addElement(new Rectangle2D.Float(x,y,10,10));
x+=10;
}
x=210;
y=220;
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e)//控制蛇的方向
{
switch (e.getKeyCode())
{
case KeyEvent.VK_LEFT:
direction="left"; break;
case KeyEvent.VK_RIGHT:
direction="right";break;
case KeyEvent.VK_UP:
direction="up";break;
case KeyEvent.VK_DOWN:
direction="down";break;
}
}
void move()//蛇的移动
{
while(true)
{
try{Thread.sleep(200);}
catch(InterruptedException e){return;}
lastsnakeElement=snakelength.lastElement();
this.eat();
if (eatfood==false) snakelength.remove(snakelength.size()-1);
if (direction=="left") x-=10;
else if(direction=="right") x+=10;
else if(direction=="up") y-=10;
else if(direction=="down") y+=10;
snakelength.insertElementAt(new Rectangle2D.Float(x,y,10,10),0);
firstsnakeElement=snakelength.firstElement();
repaint();
}
}
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D)g;
paintsnake(g2);
if (foodshow)
{
paintrect(g2);
foodshow=false;
}
}
void paintsnake(Graphics2D g2)//画蛇身
{
if (firststart)//初始化画蛇身
{
for(int i=0;i<5;i++)
{
g2.fill(snakelength.elementAt(i));
}
firststart=false;
}
else
{
if (eatfood==false)
{
g2.clearRect((int)lastsnakeElement.getX(),(int)lastsnakeElement.getY(),10,10);
g2.fill(snakelength.elementAt(0));
}
else
{
g2.fill(snakelength.elementAt(0));
}
}
}
void paintrect(Graphics2D g2)//画食物
{
g2.fill(new Rectangle2D.Float(((int)(Math.random()*1000)%30)*10,((int)(Math.random()*1000)%30)*10,10,10));
}
void eat()
{
if (food.getX()==firstsnakeElement.getX() && food.getY()==firstsnakeElement.getY()) {eatfood=true;foodshow=true;}
}
}
public class SnakeMain
{
public static void main(String args[])
{
JFrame jf=new JFrame();
Snake snake=new Snake();
jf.getContentPane().add(snake);
jf.setSize(300,300);
jf.setVisible(true);
jf.addKeyListener(snake);
snake.move();
}
}
我认为错误是在this.eat();这个位置,但我不知道为什么错了