键盘按下某键 停止运行java_JAVA 键盘监听当中,释放键盘并没有停止运动

package plane;

import java.awt.Graphics;

import java.awt.Image;

import java.awt.event.KeyAdapter;

import java.awt.event.KeyEvent;

import util.GameUtil;

import util.MyFrame;

//定义图片出现的初始位置

public class PlaneGameFrame extends MyFrame{

Image bg = GameUtil.getImage("backgroundIMG/bg.png");

Plane p = new Plane("backgroundIMG/3.png",20,20);

public void paint(Graphics g) {

g.drawImage(bg,0,0,null);

p.draw(g);

}

public static void main(String[] args) {

new PlaneGameFrame().launchFrame();

}

public void launchFrame() {

super.launchFrame();

//增加键盘监听

addKeyListener(new KeyMonitor());

}

// 定义为内部类,可方便使用外部的普通属性

class KeyMonitor extends KeyAdapter{

public void keyPressed(KeyEvent e) {

System.out.println("按下:"+e.getKeyCode());

switch(e.getKeyCode()) {

case 37:

p.left = true;

break;

case 39:

p.right = true;

break;

case 38:

p.up = true;

break;

case 40:

p.down = true;

break;

default:

break;

}

}

}

public void keyReleased(KeyEvent e) {

System.out.println("释放:"+e.getKeyCode());

switch(e.getKeyCode()) {

case 37:

p.left = true;

break;

case 39:

p.right = true;

break;

case 38:

p.up = true;

break;

case 40:

p.down = true;

break;

default:

break;

}

}

}

这是窗口加载的代码

package plane;

import java.awt.Graphics;

import java.awt.Image;

import java.awt.event.KeyEvent;

import util.GameUtil;

public class Plane {

Image img;

double x,y;

int speed = 10;

boolean left,up,right,down;

public void draw(Graphics g)

{

g.drawImage(img,(int)x,(int)y,null);

move();

}

public Plane(String imgpath, double x, double y) {

super();

this.img = GameUtil.getImage(imgpath);

this.x = x;

this.y = y;

}

public Plane() {

}

public void move() {

if(left) {

x -= speed;

}

if(right) {

x += speed;

}

if(up) {

y -= speed;

}

if(down) {

y += speed;

}

}

}

这个是运动物体的类

求助各位帮我看下到底哪里除了问题

显示的结果是,按方向键确实可以移动,可是释放键并不停止移动

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页