0

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?

Imperative
  • 3,138
  • 2
  • 25
  • 40
Noorullah
  • 11
  • 3
  • Possible duplicate of [Application wide keyboard shortcut - Java Swing](http://stackoverflow.com/questions/100123/application-wide-keyboard-shortcut-java-swing) – Reinard Apr 19 '16 at 08:34
  • Do you want global short cuts or short cuts attached to menu items and/or other buttons? – MadProgrammer Apr 19 '16 at 09:43

1 Answers1

1

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);
    }
}
Timmos
  • 3,215
  • 2
  • 32
  • 40