Ky6000
Ky6000

Reputation: 103

Keybinding in Java not working

This is issue is probably very small but the frustrates the hell out of me. I've been trying to make a small program to get my head around keybinds, but its giving errors.

    public static void key() {
    //another way to use the JComonent class?
    JComponent component;
    Main main = new Main();
    JFrame frame = new JFrame();
    frame.getContentPane().add(main);

    Action test = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
        }
    };
    //"The local variable component may not have been initialized" for component
    component.getInputMap().put(KeyStroke.getKeyStroke("A"), "test");
    component.getActionMap().put("test", test);
}

Thanks for any help.

Upvotes: 0

Views: 58

Answers (1)

Jens
Jens

Reputation: 69495

You never assign a value to JComponent component; Thats why you get the error.

You can change it to JComponent component = null; and the error is gone. But you get a NPE in the line component.getInputMap().put(KeyStroke.getKeyStroke("A"), "test"); at runtime, so you have to assign a proper value to `component.

Upvotes: 1

Related Questions