我的Key Listener出了什么问题?它根本没有按下按键

时间:2017-05-08 20:04:24

标签: java swing keylistener keyevent

public class Maze extends JPanel
{

    int x = 0;
    int y = 0;
    int previousX = x;
    int previousY = y;

    public Maze()
    {
        setBackground(Color.WHITE);

        addKeyListener(new ArrowListener());
        setPreferredSize(new Dimension(200, 200));
        setFocusable(true);
        requestFocusInWindow();
    }

    public void paintComponent(Graphics page)
    {
        super.paintComponent(page);
        page.setColor(Color.WHITE);
        page.fillRect(previousX, previousY, 10, 10);
        page.setColor(Color.magenta);
        page.fillRect(x, y, 10, 10);

    }

    private class ArrowListener implements KeyListener
    {

        public void keyPressed(KeyEvent event)
        {
            System.out.println("pressed");
            previousX = x;
            previousY = y;

            switch(event.getKeyCode())
            {

            case KeyEvent.VK_W:
                if(y >= 0)
                    y--;
                System.out.println("up");
                break;

            case KeyEvent.VK_S:
                if(y <= 100)
                    y++;
                System.out.println("Down");
                break;

            case KeyEvent.VK_A:
                if(x >= 0)
                    x--;
                System.out.println("Left");
                break;

            case KeyEvent.VK_D:
                if(x <= 100)
                    x++;
                System.out.println("Right");


            }
            repaint();
        }

        public void keyReleased(KeyEvent event){}

        public void keyTyped(KeyEvent event){}

    }
}

println行根本不打印,表明它甚至没有进入keyPressed方法。我究竟做错了什么?它应该做的就是在屏幕周围移动一个矩形。

1 个答案:

答案 0 :(得分:2)

import javax.swing.JFrame;

public class Main {

    static Maze m = new Maze();
    static JFrame frame = new JFrame();

    public static void main(String[] args) {
        frame.setSize(300, 300);
        frame.add(m);
        frame.pack();
        frame.setVisible(true);
    }

}

我快速编写了这个Main类并测试了你的代码。它对我有用。