I have created an application in Java and now I want to add keyboard shortcuts to all of swing component.
What will be the best way to achieve this? Are there any API's to use?
I have created an application in Java and now I want to add keyboard shortcuts to all of swing component.
What will be the best way to achieve this? Are there any API's to use?
You need to use the InputMap
and ActionMap
of the components. For a tutorial, check here.
The input map (from the Javadoc):
InputMap provides a binding between an input event (currently only KeyStrokes are used) and an Object.
The action map (from the Javadoc):
ActionMap provides mappings from Objects (called keys or Action names) to Actions.
So basically you need to bind a input event to a key which in turn is then mapped onto an Action, and an Action is what "executes" what you actually want to execute.
Here's a little program that spawns a button when you press alt+shift+X.
public class KeyBindingExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
KeyBindingExample.start();
}
});
}
private static void start() {
final JFrame frame = new JFrame("Action binding example");
final JPanel content = new JPanel();
Action myAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JButton button = new JButton ("Hello world!");
content.add(button);
frame.pack();
}
};
content.getInputMap().put(KeyStroke.getKeyStroke("alt shift X"), "MyActionDefinition");
content.getActionMap().put("MyActionDefinition", myAction);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(content);
frame.pack();
frame.setVisible(true);
}
}