CavalryOuO
2017-05-20 13:09
采纳率: 62.5%
浏览 1.7k
已采纳

java键盘监听无法触发

程序只有一个JFrame,应该不是焦点问题。

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

import javax.swing.JFrame;

public class GameInterface extends JFrame implements KeyListener{
Tank tank=new Tank();
Bullet bullet=new Bullet();
TankController tc=new TankController();
public GameInterface() {
this.addKeyListener(this);
this.setFocusable(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);

setBounds(0,0,1500,1000);
setVisible(true);

}

public void paint(Graphics g){
while(true){
tank.clearTank(g);
tank.clearMyTank(g);
tc.tankDirection();
tank.draw(g);

tank.drawMyTank(g);
bullet.draw(g);
}

}

public static void main(String[] args){
new GameInterface().repaint();
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("r");

switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT:
Tank.myTank.Dirction=Tank.RIGHT;
Tank.myTank.x+=20;
break;
case KeyEvent.VK_LEFT:
Tank.myTank.Dirction=Tank.LEFT;
Tank.myTank.x-=20;
break;
case KeyEvent.VK_UP:
Tank.myTank.Dirction=Tank.UP;
Tank.myTank.y-=20;
break;
case KeyEvent.VK_DOWN:
Tank.myTank.Dirction=Tank.DOWN;
Tank.myTank.y+=20;
break;}

}

@Override
public void keyReleased(KeyEvent e) {

}

@Override
public void keyTyped(KeyEvent e) {

}

}

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题