键绑定不起作用,Java SE,Swing

Key bindings don't work, Java SE, Swing

我正在尝试向我的 JButton 添加快捷方式。我已经阅读了 How to Use Key Bindings tutorial and I also have read this page How to use Key Bindings instead of Key Listeners 和一大堆关于键绑定的其他问题,但没有找到适合我的答案

我试过的:

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();
    }

}

我也试过这样做:getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), "doSmth");

但似乎没有任何效果,我做错了什么?

您的 Action 有一个名为 isEnabled 的方法,您已实施。上面的 Javadoc 指出:

/**
 * 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
 */

由于您 return 是一个硬编码的 falseAction 永远不会启用并且永远不会调用 actionPerformed 方法。您的问题不在于绑定,而在于操作本身!

一个简单的解决方法是将 isEnabled 更改为 return true,或者更简单的是,使用 AbstractAction 代替 Action,并且仅覆盖 actionPerformedAbstractAction 有点像 "I don't care about all this stuff, just give me the simplest thing possible with one method to implement!")