【问题标题】:Key bindings don't work, Java SE, Swing键绑定不起作用,Java SE,Swing
【发布时间】:2016-07-28 12:02:07
【问题描述】:

我正在尝试向我的 JButton 添加快捷方式。我已经阅读了How to Use Key Bindings 教程,并且我还阅读了此页面 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");

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

【问题讨论】:

  • 你的第一个例子对我有用。 “并且具有actionPerformed 功能”是什么意思?
  • 发布minimal reproducible example。您的问题不在您提供的代码 sn-ps 中。
  • 我已经编辑了问题,现在它显示NextCardListener。我的意思是它应该这样做,对不起
  • 提示:添加@user1803551(或重要的@)以通知此人有新评论。在讨论这个主题时,请发布 MCVE(在此之前由于缺少一个而关闭)。
  • @EthanGills Pro 提示:isEnabled() 方法不适合大便和咯咯笑。你想在那里返回true,而不是false。一个更简单的方法是使用AbstractAction 而不是Action,因为您显然不知道它们是如何工作的。另外,请不要在示例代码中发誓。

标签: java swing keyboard-shortcuts key-bindings


【解决方案1】:

您的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,并仅覆盖actionPerformedAbstractAction 有点像“我不不用管这些东西,只要给我最简单的东西,用一种方法来实现!”)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多