KeyListener没有响应键输入

时间:2016-01-14 01:09:43

标签: java swing jframe jpanel keylistener

所以我看到了几个问题。他们都说你不应该使用Keylistener而是使用KeyBinding。但是当我去使用Keybinding时它不起作用。我知道我可能应该使用KeyBinding的东西,但有一种方法可以修复我的代码,以便KeyListener工作。谢谢。

游戏类:

public class Game extends JFrame implements KeyListener{
    public static int ppx,ppy;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500,600);
        frame.add(new THIng());
        frame.setVisible(true);
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keycode = e.getKeyCode();
        if(keycode == KeyEvent.VK_D){
            System.out.println("Debug");
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

}

THIng Class:

    public class THIng extends JPanel{
    public static int px,py,pwid,phei;

    public void main(String[]args){
        Timer timer;
        timer = new Timer(60,
                new ActionListener(){
                    public void actionPerformed(ActionEvent evt){
                        p();
                    }
                }
        );
    }
    public THIng(){

        px = Game.ppx;py = Game.ppy;pwid = 50;phei = pwid;
    }

    @Override
    public Dimension getPreferredSize(){
        return new Dimension(500,600);
    }
    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics p = (Graphics)g;
        p.drawRect(px,py,pwid,phei);

    }
    public void p(){
        repaint();
    }

}

2 个答案:

答案 0 :(得分:0)

您不必创建构造函数,只需添加frame.addKeyListener(this);,即可在其中设置JFrame的其他属性。

答案 1 :(得分:-1)

正如MadProgrammer指出正确的做法是使用Key Bindings API,你可以逐步看到Key Bindings API

添加一个构造函数,添加一个键侦听器,并在你的main中使它成为类Game而不是JFrame

public class Game extends JFrame implements KeyListener{
    public static int ppx,ppy;

    public Game(String string) {
        addKeyListener(this);
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
        Game frame = new Game("Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500,600);
        frame.add(new THIng());

        frame.setVisible(true);

    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keycode = e.getKeyCode();
        if(keycode == KeyEvent.VK_D){
            System.out.println("Debug");
        }
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }



}