[英]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.