设置键绑定以执行与我的动作侦听器中相同的操作

oip*_*psl 2 java swing event-handling

我有一个附加到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
    }
}
Run Code Online (Sandbox Code Playgroud)

看起来有点乏味,不得不添加一个Action和一个ActionListener来做同样的事情.也许我没有看到它,但有没有办法减少代码,所以我可以消除Action并只使用actionListener?我在考虑在getActionMap().put()方法中切换buttonListener参数,但该方法只接受Action类型.

Mar*_*iot 5

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);
}
Run Code Online (Sandbox Code Playgroud)