java - 设置键绑定(bind)以执行与我的 Action 监听器中相同的 Action

标签 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
    }
}

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

最佳答案

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

关于java - 设置键绑定(bind)以执行与我的 Action 监听器中相同的 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6824406/

相关文章:

java - 如何使用服务监控文件夹

java - JTable 中 DnD 行的自定义数据风格

java - 在 jframe 中为 jpanel 调用 paintcomponent

python - YAML 列表 -> Python 生成器?

c# - WPF从列表框中删除项目

java - 与 “JAVA exception handling mindset”相比, “C++ exception handling”是什么?

java - 测试包含日期字段的对象

java - 覆盖 Flamingo 的 JCommandButton 的默认前景色

java - 如何在Java中更改图表比例

C# - 在 PowerStatus 更改时引发事件