日期:2014-05-20  浏览次数:20608 次

前辈高手们!快快进来!帮帮小辈我答疑解惑一下吧!
小菜我近日根据书上写了个小代码:
import java.awt.*;
import java.awt.event.*;

public class KeyEvent2 extends Frame{
Button man;

public KeyEvent2(String title){
super(title);
setLayout(null);
this.setSize(200,200);
man=new Button("MAN");
man.setBounds(100,100,40,20);
man.setBackground(Color.BLUE);
man.setForeground(Color.WHITE);
this.add(man);
man.addKeyListener(new KeyHandler());

}
public static void main(String[] args){
KeyEvent2 me=new KeyEvent2("keyMan");
me.setVisible(true);
}


class KeyHandler extends KeyAdapter{
public void keyPressed(KeyEvent e){
String direction=e.getKeyText(e.getKeyCode());
//int direction=e.getKeyCode();

int x=man.getX();
int y=man.getY();
if(direction.equals("Right")) x+=10;
else if(direction.equals("Left")) x-=10;
else if(direction.equals("Down")) y+=10;
else if(direction.equals("Up")) y-=10;
man.setLocation(x,y);


/*if(direction==KeyEvent.VK_RIGHT) x+=10;
else if(direction==KeyEvent.VK_LEFT) x-=10;
else if(direction==KeyEvent.VK_DOWN) y+=10;
else if(direction==KeyEvent.VK_UP) y-=10;
man.setLocation(x,y);*/


}
}
}
以上代码可以编译通过,但是蓝色部分的代码运行完按上下左右键一点没反应都没有。用红色部分的代码却可以。
小弟我把equals里面的字符串大小写都试过了结果都不行,不知道是哪里出问题了,虚心求各位前辈帮帮忙答疑解惑一下

------解决方案--------------------

看上图,按键的名称都是首字母大写,如Left,Right,建议使用KeyCode来判断按了哪个键,
Java飞虎队欢迎各路菜鸟老鸟加入一起交流讨论。群号105098806