我试图使用KeyListener移动一个矩形但我的输入没有被读取

时间:2015-05-30 16:14:29

标签: java swing

我正在为我的编码课做最后的项目,我想制作一个简单的视频游戏,但我遇到键盘输入问题。编译代码时,会创建框架并绘制矩形,但我的键盘输入都不起作用。

public class GameProject extends JPanel implements ActionListener, KeyListener {
    Timer tm = new Timer(5,this);
int x = 0;
int y = 0;
static int velX = 0;
int velY = 0;  

public void Game(){
    tm.start();
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);
    }

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.RED);
    g.fillRect(x, y, 50, 30);
}

public void actionPerformed(ActionEvent e){
    x = x + velX;
    y = y + velY;
    repaint();
}

public void keyPressed(KeyEvent e){
    int c = e.getKeyCode();

    if (c == KeyEvent.VK_LEFT){
        velX = -1;
        velY = 0;
    }
    if(c == KeyEvent.VK_UP){
        velX = 0;
        velY = -1;
    }
    if (c == KeyEvent.VK_RIGHT){
        velX = 1;
        velY = 0;
    }
    if (c == KeyEvent.VK_DOWN){
        velX = 0;
        velY = 1;
    }
}

public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}

public static void main(String[] args){
    JFrame frame = new JFrame("Test Game");
    GameProject game = new GameProject();
    frame.setSize(600, 400);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(game);

}

}

0 个答案:

没有答案