java 键盘监听事件

package tank.world;

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

public class Object extends JPanel implements KeyListener {
public static final int U = 1;
public static final int D = 2;
public static final int L = 3;
public static final int R = 4;
public static final int S = 5;
protected int state = U;

public static BufferedImage up;
public static BufferedImage down;
public static BufferedImage right;
public static BufferedImage left;
public static BufferedImage bullet;
static {
right = TankObject.loadImage("1.png");
up = TankObject.loadImage("2.png");
down = TankObject.loadImage("3.png");
left = TankObject.loadImage("yellowL.png");
bullet=TankObject.loadImage("3.gif");
}


int x = 400;
int y = 600;

public void outOfBounds() {
if (this.y >= 800) {
y = 800;
}
}

public void paint(Graphics g) {
super.paint(g);
switch (state) // 调用常量
{
case U: // 上 //如果按键是上 的时候 就调用 向上的图片
g.drawImage(up, x, y, null);
System.out.println("111");
break;
case D: // 下
g.drawImage(down, x, y, null);// 如果按键是下 的时候 就调用 向下的图片
System.out.println("222");
break;
case L: // 左
g.drawImage(left, x, y, null);// 如果按键是左 的时候 就调用 向左的图片
System.out.println("333");
break;
case R: // 右
g.drawImage(right, x, y, null);// 如果按键是右 的时候 就调用 向右的图片
System.out.println("444");
break;
case S: // 空格
g.drawImage(bullet, 100, 100, null);// 如果按键是空格 的时候 就调用 子弹的图片
System.out.println("555");
break;

}
}


public void keyPressed(KeyEvent e) { // 当某键被按下时的方法
// System.out.println("被按下"+(char)e.getKeyCode());
switch (e.getKeyCode()) {
case KeyEvent.VK_UP: // 上
y -= 10; // 速度数值,可以调节快慢
if (this.y >= 800) {
y = 800;
}
if (this.y <= 0) {
y = 0;
}
this.repaint(); // 调用repaint()方法,重新绘制坦克位置
state = U;
break;
case KeyEvent.VK_DOWN: // 下
y += 10; // 速度数值,可以调节快慢
if (this.y >= 700) {
y = 700;
}
if (this.y <= 0) {
y = 0;
}
this.repaint(); // 调用repaint()方法,重新绘制坦克位置
state = D;
break;
case KeyEvent.VK_LEFT: // 左
x -= 10;
if (this.x >= 800) {
x = 800;
}
if (this.x <= 0) {
x = 0;
} // 速度数值,可以调节快慢
this.repaint(); // 调用repaint()方法,重新绘制坦克位置
state = L;
break;
case KeyEvent.VK_RIGHT: // 右
x += 10; // 速度数值,可以调节快慢
if (this.x >= 735) {
x = 735;
}
if (this.x <= 0) {
x = 0;
}
this.repaint(); // 调用repaint()方法,重新绘制坦克位置
state = R;
break;
case KeyEvent.VK_SPACE:
state = S;
this.repaint();
break;
}
}

public void keyTyped(KeyEvent e) {
}

public void keyReleased(KeyEvent e) {
}
}

原文地址:https://www.cnblogs.com/xyk1987/p/8242133.html