我正在尝试向我的 JButton 添加快捷方式。我读过 How to Use Key Bindings教程,我也阅读了此页面 How to use Key Bindings instead of Key Listeners还有一大堆关于键绑定(bind)的其他问题,但我还没有找到任何答案
我尝试过的:
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");
/p>
但似乎没有任何效果,我做错了什么?
最佳答案
您的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
方法。您的问题不在于绑定(bind),而在于操作本身!
一个简单的解决方法是将 isEnabled
更改为返回 true,或者更简单,使用 AbstractAction
代替 Action
,并覆盖只有 actionPerformed
(AbstractAction
有点像“我不关心所有这些东西,只要给我一个可能实现的最简单的方法!”)
关于java - 键绑定(bind)不起作用,Java SE,Swing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38635795/