我有一个附加到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类型。
答案 0 :(得分:5)
Action
扩展了ActionListener
,因此您应该能够定义单个Action
,并在需要ActionListener
的任何地方使用它。
e.g。
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);
}
答案 1 :(得分:4)
JRootPane有一个方法setDefaultButton(...)
可以做你想要的。您需要从顶级容器中获取根窗格,然后您可以调用此方法传递对JButton的引用,并且当在GUI上按下enter时它将执行其操作。当你想到它时,这是有道理的,因为“输入”是一个特殊的键,其行为应该是GUI的责任,而不是单个按钮。