[英]Key bindings don't work, Java SE, Swing
我正在尝试为我的JButton添加一个快捷方式。 我已经阅读了如何使用键绑定教程,我也阅读了本页如何使用键绑定而不是键监听器和关于键绑定的其他问题的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");
但似乎没有什么工作,我做错了什么?
您的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
( AbstractAction
是一种“我不关心所有这些东西,只是给我最简单的用一种方法实现的事情!“)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.