当前位置: 代码迷 >> Java相关 >> 这个程序有点小问题
  详细解决方案

这个程序有点小问题

热度:256   发布时间:2006-07-09 14:16:48.0
这个程序有点小问题
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 food=true;
private Rectangle2D.Float lastsnakelength;
private boolean first=true;
Snake()
{
this.addKeyListener(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;}
lastsnakelength=snakelength.lastElement();
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);
repaint();
}
}
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D)g;
paintsnake(g2);
if (food)
{
paintrect(g2);
food=false;
}
}
void paintsnake(Graphics2D g2)//画蛇身
{
if (first)//初始化画蛇身
{
for(int i=0;i<5;i++)
{
g2.fill(snakelength.elementAt(i));
}
first=false;
}
else
{
g2.clearRect((int)lastsnakelength.getX(),(int)lastsnakelength.getY(),10,10);
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));
}
}
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();
}
}
为什么没有键盘响应,只要把顶级窗口注册监听事件,当触发键盘事件的时候才有响应?而且为什么蛇走过的地方会有痕迹?
----------------解决方案--------------------------------------------------------

键盘事件的监听,需要该组件才获得输入焦点
一般顶级窗口才能获得焦点
走过的蛇有痕迹,可能是你的蛇没有删掉蛇的身体或者就是你没有重新盖掉重画


----------------解决方案--------------------------------------------------------
  相关解决方案