Java KeyListener类

时间:2014-01-14 12:55:53

标签: java user-interface keylistener pacman

我有一个Keylistener课程用于游戏我正在制作一些错误的游戏。我似乎无法通过关键点击获得pacman的举动。似乎永远不会调用Keylistener方法。我对Java和GUI界面比较陌生,所以如果我的编码有点生疏,请原谅我。

import java.awt.event.*;

public class PacRunner implements ActionListener, KeyListener
{
    private static Grid gr;
    public static void main (String[] args)
    {   
    gr = new Grid();
    gr.addGhost(new Location(4,11));
    gr.movePac(new Location(6,11));
    gr.show();
    }

   public void keyPressed(KeyEvent e)
   {
        if(e.getKeyCode() == KeyEvent.VK_UP) gr.move(Location.UP);          
        else if(e.getKeyCode() == KeyEvent.VK_DOWN) gr.move(Location.DOWN);
        else if(e.getKeyCode() == KeyEvent.VK_LEFT) gr.move(Location.LEFT);
        else if(e.getKeyCode() == KeyEvent.VK_RIGHT) gr.move(Location.RIGHT);
    }


    public void keyReleased(KeyEvent e) {}

    public void keyTyped(KeyEvent e) {}


    @Override
    public void actionPerformed(ActionEvent e) {}
}

2 个答案:

答案 0 :(得分:0)

你可能忘记的是你的主要方法是添加这行代码:

component.addKeyListener(keyListener)

答案 1 :(得分:0)

您尚未注册KeyListener。必须添加KeyListener。

java.awt.Component类包含方法addKeyListener(KeyListener l)

您必须确定要拦截事件的java.awt.Component。确定该Component后,您将使用PacRunner作为KeyListener参数调用此方法:

component.addKeyListener(myPacRunner);

或者,如果从PacRunner实例中调用该方法:

component.addKeyListener(this);

为了在您提供的代码中实现此模式,假设类Grid扩展Component,您将首先实例化您的PacRunner,然后将该PacRunner实例添加为KeyListener Grid

public static void main (String[] args)
{
    PacRunner myPacRunner = new PacRunner(); // An Empty constructor inherited from Object
    gr = new Grid();
    gr.addKeyListener(myPacRunner);
    ...
}

对该主题进行更全面的处理。请参阅Java教程中的How to Write a Key Listener