Ethan Gills Ethan Gills - 8 months ago 47
Java Question

Key bindings don't work, Java SE, Swing

I'm trying to add a shortcut to my JButton. I've read How to Use Key Bindings tutorial and I also have read this page How to use Key Bindings instead of Key Listeners and a loooooooooooooot of other questions about key bindings, but haven't found any answer for me

What I've tried:

public class Example extends JFrame {

public static void main(String args[]) {
Example example = new Example();

Action action = new Action() {
public Object getValue(String key) {
return null;

public void putValue(String key, Object value) {


public void setEnabled(boolean b) {


public boolean isEnabled() {
return false;

public void addPropertyChangeListener(PropertyChangeListener listener) {


public void removePropertyChangeListener(PropertyChangeListener listener) {


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);



I've also tried to make it like that:
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), "doSmth");

But nothing seems to be working, what am I doing wrong?


Your Action has a method called isEnabled that you've implemented. The Javadoc on it states:

 * 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

Since you return a hardcoded false, the Action is never enabled and the actionPerformed method is never called. Your problem is not the binding, it's the action itself!

A simple fix is to change isEnabled to return true, or, even simpler yet, use AbstractAction in place of Action, and override only actionPerformed (AbstractAction is kind of the "I don't care about all this stuff, just give me the simplest thing possible with one method to implement!")