11

In the following program, why does hitting the a key print "hello, world" while hitting CTRL+a doesn't?

import java.awt.event.*;
import javax.swing.*;

public class KeyStrokeTest {
    public static void main(String[] args) {
        JPanel panel = new JPanel();

        /* add a new action named "foo" to the panel's action map */
        panel.getActionMap().put("foo", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("hello, world");
                }
            });

        /* connect two keystrokes with the newly created "foo" action:
           - a
           - CTRL-a
        */
        InputMap inputMap = panel.getInputMap();
        inputMap.put(KeyStroke.getKeyStroke(Character.valueOf('a'), 0), "foo");
        inputMap.put(KeyStroke.getKeyStroke(Character.valueOf('a'), InputEvent.CTRL_DOWN_MASK), "foo");

        /* display the panel in a frame */
        JFrame frame = new JFrame();
        frame.getContentPane().add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }
}

How could I fix it that CTRL+a works as well?

Fabrizio
  • 7,603
  • 6
  • 44
  • 104
Thomas
  • 17,016
  • 4
  • 46
  • 70

3 Answers3

22

I find it easier to use:

KeyStroke a = KeyStroke.getKeyStroke("A");
KeyStroke controlA = KeyStroke.getKeyStroke("control A");

or:

KeyStroke controlA = KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK);
camickr
  • 321,443
  • 19
  • 166
  • 288
7

Dude, use this

inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK), "foo");
bragboy
  • 34,892
  • 30
  • 114
  • 171
  • Interesting I made my suggestion before this posting, plus I gave you other alternatives that you might be able to use in different situations. I guess I won't go to all the trouble the next time. – camickr Mar 11 '10 at 16:30
  • 1
    @Thomas: I dont know whether I am correct, but the reason that your code might have not worked because in the first case, you were referring to a simple character 'a'. Where-in in the second case you are referring a combination of keys which is an ASCII and a scan value(Ctrl key). I feel it should have been associated with events properly. – bragboy Mar 11 '10 at 18:48
  • @camickr - I'm sorry, that was an honest mistake. – Thomas Mar 12 '10 at 09:52
0

Yep, the above code will work.

Big picture - Ctrl+a and a are read as different keystrokes the same as a and b would be different.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
SOA Nerd
  • 943
  • 5
  • 12