keypress中按下键没反应
以下是我的代码 本人画了一个小坦克想通过W S A D键来控制小坦克的上下左右的移动 但是按下这四个键 小坦克不动!如果把这四个键换成键盘上的上下左右键小坦克能动!请怎样解决!要求通过W S A D键来控制小坦克的上下左右的移动!谢谢各位了!
package mytank_002;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class MyTank_002 extends JFrame{
MyPanel mp = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
MyTank_002 t1 = new MyTank_002();
}
public MyTank_002()
{
mp = new MyPanel();
this.add(mp);
//注册监听
this.addKeyListener(mp);
this.setSize(400,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
//我的面板
class MyPanel extends JPanel implements KeyListener
{
//定义一个我的坦克
MyTank mytank = null;
public MyPanel()
{
mytank = new MyTank(100, 100);
}
public void paint(Graphics g)
{
super.paint(g);
g.fillRect(0,0,400,300);
this.drawTank(mytank.getX(), mytank.getY(), g, 0, 1);
}
//画坦克的函数
public void drawTank(int x,int y,Graphics g,int direct,int type)
{
//判断什么类型的坦克
switch(type)
{
case 0:
g.setColor(Color.CYAN);
break;
case 1:
g.setColor(Color.YELLOW);
break;
default:
g.setColor(Color.BLACK);
break;
}
// 判断方向
switch(direct)
{
//向上
case 0:
//1画出左边的矩形
g.fill3DRect(x, y,5, 30,false);
//2画出右边的矩形
g.fill3DRect(x+15, y,5, 30,false);
//3画出中间的矩形
g.fill3DRect(x+5, y+5,10,20,false);
//4画出圆形
g.fillOval(x+5, y+10,10,10);
//5画出直线
g.drawLine(x+10, y+10,x+10,y);
break;
}
}
// 键按下
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
// W向上 S向下 D向右 A向左
if(e.getKeyCode()==KeyEvent.VK_W)
{
//设置我的坦克的方向 向上
this.mytank.setDirect(0);
this.mytank.moveUp();
}
else if(e.getKeyCode()==KeyEvent.VK_D)
{
//向右
this.mytank.setDirect(1);
this.mytank.moveRight();
}
else if(e.getKeyCode()==KeyEvent.VK_S)
{
//向下
this.mytank.setDirect(2);
this.mytank.moveDown();
}
else if(e.getKeyCode()==KeyEvent.VK_A)
{
//向左
this.mytank.setDirect(3);
this.mytank.moveLeft();
}
this.repaint();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
//定义坦克类
class Tank
{
//坦克的横坐标
int x = 0;
//坦克的纵坐标
int y = 0;
//坦克的方向 0向上 1向右 2向下 3向左
int direct = 0;
//坦克的速度
int speed = 1;
public Tank(int x, int y)
{
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getDirect() {
return direct;
}
public void setDirect(int direct) {
this.direct = direct;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
}
//我的坦克类
class MyTank extends Tank
{
public MyTank(int x, int y) {
super(x, y);
// TODO Auto-generated constructor stub
}
//坦克向上移动
public void moveUp()
{
this.y-=this.speed;
}
//坦克向右移动