javaswingkey-bindingsjcomponentkey-events

MouseEvents are Captured but not KeyEvents Java JComponant


I'm working on an old game project called Lemmings, and the Principle Game Panel is working well and receiving the MouseEvents but not the KeyEvents, which is not very logic for me, so I copied down the Code of this file for you guys to see whats going on.

The GamePanel class extends JComponent SWING class

public class GameFrame {

private class GamePanel extends JComponent {

    GamePanel(Dimension dim) {

        setPreferredSize(dim);

         //first version of the question was with the keyListner
        /*addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                super.keyPressed(e);
                System.out.println(e.getKeyCode());
                //nothing show up
            }
        });*/

         //I tried using this, but it didn't work
        //getInputMap().put(KeyStroke.getKeyStroke("A"), "action");

         // this works cause we use the right inputMap not the one by default 
         getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("A"), "action");
         getActionMap().put("action",new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("A is pressed");
                //now it works
            }
        });

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                System.out.println(e.getPoint());
            }
        });
        setVisible(true);
    }
}

private JFrame window;
private GamePanel panel; 

public GameFrame() {
    window = new JFrame("Test");
    window.setLocationRelativeTo(null);
    panel = new GamePanel(new Dimension(400, 400));
    window.setContentPane(panel);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
}

public static void main(String[] args) {
    new GameFrame();
}
}

UPDATE WITH SOLUTION


Solution

  • the problem can be solved simply by adding a KeyListener to the JFrame in case we don't need to create Actions and stuff

    this solution can only be possible if there are no other components focusable.

    in the file GameFrame.java in the function void init(); add

    window.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed (KeyEvent e) {
                super.keyPressed(e);
                System.out.println("test "+e.getKeyChar());
            }
        });