【问题标题】:Setting a key-binding to perform the same action as in my action listener设置键绑定以执行与我的操作侦听器中相同的操作
【发布时间】:2011-07-26 01:53:49
【问题描述】:

我有一个附加到 ActionListener 的 JButton,但我还想为该按钮添加一个快捷键以更加用户友好。比如说,用户可以点击按钮,程序执行某个功能“f”,或者用户也可以按键盘上的“Enter”来执行相同的功能 f。所以这就是我的代码的要点

private JButton button;

public static void main(String[] args){
    Action buttonListener = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
                //Perform function f    
         }
    };

button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"),
                        "test");
button.getActionMap().put("test",
                         buttonListener);

button.addActionListener(new OtherListener());
}

private class OtherListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        //Perform function f
    }
}

添加一个 Action 和一个 ActionListener 来做同样的事情似乎有点乏味。也许我没有看到它,但是有没有办法减少代码,这样我就可以消除 Action 而只使用 actionListener?我正在考虑将 getActionMap().put() 方法中的 buttonListener 参数切换为,但该方法仅采用 Action 类型。

【问题讨论】:

    标签: java swing event-handling


    【解决方案1】:

    Action 扩展了ActionListener,因此您应该能够定义一个Action 并在需要ActionListener 的任何地方使用它。

    例如

    public static void main(String[] args){
        Action buttonListener = new Action() {
             public void actionPerformed(ActionEvent e) {
                    //Perform function f    
             }
        };
        button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
            .put(KeyStroke.getKeyStroke("ENTER"), "test");
        button.getActionMap().put("test", buttonListener);
        button.addActionListener(buttonListener);
    }
    

    【讨论】:

      【解决方案2】:

      JRootPane 有一个方法setDefaultButton(...) 可以做你想做的事。您将需要从顶级容器中获取根窗格,然后您可以调用此方法传递对您的 JButton 的引用,当在 GUI 上按下 enter 时它将执行其操作。当您认为“输入”是一个特殊的键时,这是有道理的,它的行为应该由 GUI 负责,而不是单个按钮。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-27
        • 2014-09-10
        • 1970-01-01
        • 2014-05-10
        相关资源
        最近更新 更多