我有一个附加到 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/