This code works well for me to make key bindings more pleasant, via calls such as those that follow:
import java.awt.event.ActionEvent;
import javax.swing.*;
import static javax.swing.KeyStroke.getKeyStroke;
public abstract class KeyBoundButton extends JButton{
public abstract void action(ActionEvent e);
public KeyBoundButton(String actionMapKey, int key, int mask)
{
Action myAction = new AbstractAction()
{
@Override public void actionPerformed(ActionEvent e)
{
action(e);
}
};
setAction(myAction);
getInputMap(WHEN_IN_FOCUSED_WINDOW)
.put(getKeyStroke(key, mask),actionMapKey);
getActionMap().put( actionMapKey, myAction);
}
}
Calls:
button = new KeyBoundButton("WHATEVER", VK_X, CTRL_DOWN_MASK)
{
@Override
public void action(ActionEvent e)
{
JOptionPane.showMessageDialog(null,"Ctrl-X was pressed");
}
};
But I don't have a clue how to use the key name, WHATEVER
, either intelligently or otherwise, elsewhere in a program.
I wondered about button.getActionCommand()
but it returns null
, even if I insert this line after action(e)
in the class definition:
setActionCommand(actionMapKey);
What is the purpose of the key name? Am I supposed to use it somewhere in a program other than in defining the key binding?
The key name is used if you have only one listener to the events.
Usually:
This code was wrote from my memory, probably is not the actual Object names from the Java API.