Search code examples
javaswingkeyboard-shortcutsactionkeystroke

Binding key combination to JFrame


So far I've got ESC key to close the window, using the following code:

KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
    Action escapeAction = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            screen.dispose();
         }
    };
screen.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
screen.getRootPane().getActionMap().put("ESCAPE", escapeAction);

But I am wondering how I would go about adding a CTRL+A event? I remember reading about a way where you set booleans for keypressed/released, but I don't see that working with this piece of code, so I am wondering how I can implement CTRL+A.

Thank You


Solution

  • It's the second parameter of the KeyStroke.getKeyStroke(...) method that matters, as you'll want to use the InputEvent.CTRL_DOWN_MASK there to let the KeyEvent.VK_A be a control-A.

    e.g.,

    KeyStroke ctrlAKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_A,
         InputEvent.CTRL_DOWN_MASK);
    

    I wouldn't worry about using the 3 parameter method that uses a boolean since you're more interested in key press, not key down or key release.

    Regarding your comment:

    Correction to my earlier comment. It works, if I make it let's say Ctrl+W. Ctrl+A just attempts to do its native "select all" function in a textfield in the frame. Any way to avoid that?

    From the little I understand, this will be a problem if the component that has focus (such as a JTextArea) responds directly to the ctrl-A key press. To get around this, you can add the same binding to this component, but being sure to bind it to its InputMap that uses the JComponent.WHEN_FOCUSED; condition.