Tyler Neftzger
Tyler Neftzger

Reputation: 9

What is wrong with my Key Listener? It does not go into key pressed at all

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){}

    }
}

The println lines do not print at all, indicating it doesn't even go into the keyPressed method. What am I doing wrong? All it is supposed to do is move a rect around the screen.

Upvotes: 0

Views: 83

Answers (1)

atanii
atanii

Reputation: 236

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);
    }

}

I wrote this Main class quickly and tested your code. It worked for me.

Upvotes: 2

Related Questions