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;
}
}
}
这个是运动物体的类
求助各位帮我看下到底哪里除了问题显示的结果是,按方向键确实可以移动,可是释放键并不停止移动
1 回答
互换的青春
TA贡献1797条经验 获得超6个赞
第一
我发现我提这个问题时候没有注意提问的礼仪,我的代码粘贴并没有完善好就发布出来了
第二,是我自己粗心问题没看到程序有个细节写错了
`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;
}
}`
只要把上面的true改过成false就可以了
添加回答
举报
0/150
提交
取消