Ethan
Ethan

Reputation: 104

Key bindings don't work, Java SE, Swing

I'm trying to add a shortcut to my JButton. I've read How to Use Key Bindings tutorial and I also have read this page How to use Key Bindings instead of Key Listeners and a loooooooooooooot of other questions about key bindings, but haven't found any answer for me

What I've tried:

public class Example extends JFrame {

    public static void main(String args[]) {
        Example example = new Example();
    }

    Example(){
        Action action = new Action() {
            @Override
            public Object getValue(String key) {
                return null;
            }

            @Override
            public void putValue(String key, Object value) {

            }

            @Override
            public void setEnabled(boolean b) {

            }

            @Override
            public boolean isEnabled() {
                return false;
            }

            @Override
            public void addPropertyChangeListener(PropertyChangeListener listener) {

            }

            @Override
            public void removePropertyChangeListener(PropertyChangeListener listener) {

            }

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Hello World!");
            }
        };

        JButton button = new JButton("Hello World!");
        button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("RIGHT"), "doSomething");
        button.getActionMap().put("doSomething", action);
        button.addActionListener(action);

        add(button);
        setVisible(true);
        pack();
    }

}

I've also tried to make it like that: getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), "doSmth");

But nothing seems to be working, what am I doing wrong?

Upvotes: 1

Views: 119

Answers (1)

Ordous
Ordous

Reputation: 3884

Your Action has a method called isEnabled that you've implemented. The Javadoc on it states:

/**
 * Returns the enabled state of the <code>Action</code>. When enabled,
 * any component associated with this object is active and
 * able to fire this object's <code>actionPerformed</code> method.
 *
 * @return true if this <code>Action</code> is enabled
 */

Since you return a hardcoded false, the Action is never enabled and the actionPerformed method is never called. Your problem is not the binding, it's the action itself!

A simple fix is to change isEnabled to return true, or, even simpler yet, use AbstractAction in place of Action, and override only actionPerformed (AbstractAction is kind of the "I don't care about all this stuff, just give me the simplest thing possible with one method to implement!")

Upvotes: 3

Related Questions