Jjack
Jjack

Reputation: 1358

How to add a keylistener to JFrame Subclass

I implemented all of the necessary methods and added the "implements KeyListener" and added the addKeyListener and setFocus(true) but I get no keyresponses. The JFrame includes a canvas class that I created. Here is the constructor for the window class.

    setBounds(0,0, width, height);
    setIgnoreRepaint(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    add(MainCanvas.Instance());
    this.getContentPane().addKeyListener(this);
    pack();
    setVisible(true);

    if (thread == null)
    {
        thread = new Thread(this);
    }

    thread.start();

Upvotes: 1

Views: 2861

Answers (2)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

Only the focus component will get sent the key events; you need to call requestFocus() on your Canvas.

Upvotes: 2

Suresh Kumar
Suresh Kumar

Reputation: 11787

You should add the KeyListener to the the Canvas instead of JFrame. When you add any component to JFrame (e.g. add(MainCanvas.getInstance()), with default layout (BorderLayout), the component occupies the JFrame view and all your key strokes are being sent to the Canvas and not to JFrame. Try adding the KeyListener to MainCanvas instead of JFrame.

Upvotes: 1

Related Questions