简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM