Search code examples
javakey-bindings

Keybinding not calling AbstractAction


I am making a game where the user has to press keys to move around. I am using keybindings but they are not working. The keybindings are supposed to call the Wp class and print "W pressed", but nothing happens. Here's the code:

public class SO extends JFrame {

    public static void main(String[] args) {
        new SO();
    }
    C c;
    public SO(){
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(500, 500);
        c=new C();
        c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("W"), "wp");
        c.getActionMap().put("wp", new Wp());
        this.setVisible(true);
    }
    private class C extends JComponent {
        public void paint(Graphics g){}
    }
    private class Wp extends AbstractAction {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            System.out.println("W pressed");
        }

    }

}

Solution

  • I forgot to add the C to the JFrame...