Java – Utilising both a mouse listener and key listener in Java

focusjavakeylistenermouselistenerswing

I have a program which moves a an object to the left or to the right.
I want to utilise it so that it works with both a mouse listener and a key listener. With both the left arrow key and a left mouse click carrying out the same option. And vice versa for the right mouse key or arrow key.
My code currently looks a bit like this, I've cut out some unnecessary parts.

public class TetrisApplet extends JApplet implements MouseListener, KeyListener {

public void init() {

        tetris.addMouseListener(this);
        tetris.addKeyListener(this);

public void mouseReleased(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON1) {
            if (x > 0 && a[x - 1][y] == 0) {
                shape.move(-20, 0);
                x--;
            }
        }
        if (e.getButton() == MouseEvent.BUTTON3) {
            if (x < 9 && a[x + 1][y] == 0) {
                shape.move(+20, 0);
                x++;
            }
        }

    }

    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        switch (keyCode) {
            case KeyEvent.VK_LEFT:
                if (x > 0 && a[x - 1][y] == 0) {
                    shape.move(-20, 0);
                    x--;
                }
                break;
            case KeyEvent.VK_RIGHT:
                if (x < 9 && a[x + 1][y] == 0) {
                    shape.move(+20, 0);
                    x++;
                }
                break;
        }
    }

So my question is, does anyone have an answer for why it won't work for keys? My program allows the object to be moved using mouse clicks, however pressing of the left arrow and right arrow keys does absolutely nothing. And I have no idea why it isn't working. I know it's probably something small that I'm just missing, but any help is greatly appreciated.

Best Answer

I think the problem has to do with focus. The component that has the focus get the key events instead of your tetris component (which doesn't have any way to grab the focus).

The quick fix is to add:

tetris.requestFocus();

in the init method because you want the focus to start in the correct component (?) and in the mouseReleased because you want to be able to grab the focus again.