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

时间:2016-07-28 12:02:08

标签: java swing keyboard-shortcuts key-bindings

我正在尝试为JButton添加一个快捷方式。我已经阅读了How to Use Key Bindings教程,我也阅读了这个页面How to use Key Bindings instead of Key Listeners以及关于键绑定的其他问题的loooooooooooooot,但是没有找到任何答案

我尝试了什么:

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");

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

1 个答案:

答案 0 :(得分:3)

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

由于您返回了硬编码false,因此永远不会启用Action,并且永远不会调用actionPerformed方法。你的问题不是绑定,而是行动本身!

一个简单的解决方法是将isEnabled更改为true,或者更简单,使用AbstractAction代替Action,并仅覆盖actionPerformed({{ 1}}有点“我不关心所有这些东西,只需用一种方法实现就可以给我最简单的东西!”)