1

I must be missing something here, but I can't figure out why the InputEvent.CTRL_DOWN_MASK nor InputEvent.CTRL_MASK work?

What I am trying to do is implement a way for Ctrl-C to issue a command in a Swing GUI. I am using the following code:

  myTextArea.getInputMap(JComponent.WHEN_FOCUSED).put(
      KeyStroke.getKeyStroke((char) 'c', /***/InputEvent.CTRL_DOWN_MASK/***/), "ctrl");
  myTextArea.getActionMap().put("ctrl", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
      System.out.println("test");
    }
  });

Notice the InputEvent.CTRL_DOWN_MASK. When I keep it in there, the action never gets performed. When I comment it out, the action works (but I am only pressing the lower-case 'c' button. Not ctrl.

Am I missing something on how to really use the CTRL_MASK for swing key events?

E.S.
  • 2,733
  • 6
  • 36
  • 71

2 Answers2

2

Am I missing something on how to really use the CTRL_MASK for swing key events?

  • you have to put this paramater to the InputMap

e.g. inputMap.put(KeyStroke.getKeyStroke(myKey, InputEvent.CTRL_DOWN_MASK), someName);

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • OP's calling `getInputMap(...).put(KeyStroke, String)` in the example. – Josh Nov 15 '13 at 20:02
  • @Eric S nothing beter as [answers about by top Swing Gurus here](http://stackoverflow.com/questions/6887296/how-to-make-an-image-move-while-listening-to-a-keypress-in-java) – mKorbel Nov 15 '13 at 20:14
  • Oops; I meant `...put(char, int)` - what I was saying is that it looks to me like OP is calling the method you're telling him to, with the modifier in the right place; the `put()` call is just chained after a `get()`. – Josh Nov 15 '13 at 20:26
1

That looks mostly right to me, but try

KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK);

instead of

KeyStroke.getKeyStroke((char) 'c', InputEvent.CTRL_DOWN_MASK);

ie, don't rely on the int interpretations of char values to pass your key code; use the "virtual keyboard" constants Java provides.

Josh
  • 1,563
  • 11
  • 16