我正在尝试为JButton添加一个快捷方式。我已经阅读了How to Use Key Bindings教程,我也阅读了这个页面How to use Key Bindings instead of Key Listeners以及关于键绑定的其他问题的loooooooooooooot,但是没有找到任何答案
我尝试了什么:
public class Example extends JFrame {
public static void main(String args[]) {
Example example = new Example();
}
Example(){
Action action = new Action() {
@Override
public Object getValue(String key) {
return null;
}
@Override
public void putValue(String key, Object value) {
}
@Override
public void setEnabled(boolean b) {
}
@Override
public boolean isEnabled() {
return false;
}
@Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
}
@Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello World!");
}
};
JButton button = new JButton("Hello World!");
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("RIGHT"), "doSomething");
button.getActionMap().put("doSomething", action);
button.addActionListener(action);
add(button);
setVisible(true);
pack();
}
}
我也尝试过这样做:getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), "doSmth");
但似乎没有任何效果,我做错了什么?
答案 0 :(得分:3)
您的Action
有一个名为isEnabled
的方法已经实施。它上面的Javadoc声明:
/**
* Returns the enabled state of the <code>Action</code>. When enabled,
* any component associated with this object is active and
* able to fire this object's <code>actionPerformed</code> method.
*
* @return true if this <code>Action</code> is enabled
*/
由于您返回了硬编码false
,因此永远不会启用Action
,并且永远不会调用actionPerformed
方法。你的问题不是绑定,而是行动本身!
一个简单的解决方法是将isEnabled
更改为true,或者更简单,使用AbstractAction
代替Action
,并仅覆盖actionPerformed
({{ 1}}有点“我不关心所有这些东西,只需用一种方法实现就可以给我最简单的东西!”)