1

This key event is not working. The same code is working for,

VK_SPACE

Its not working for control

private void jTextArea1KeyPressed(java.awt.event.KeyEvent evt) {
    if ((evt.getKeyChar() == KeyEvent.VK_CONTROL)) {
        System.out.println("CONTROL IS PRESSED");
    }
} 
mKorbel
  • 109,525
  • 20
  • 134
  • 319
FirmView
  • 3,130
  • 8
  • 34
  • 50
  • CTRL is a modifier key. I guess it doesn't fire the keyPressed event. – Sean Patrick Floyd Sep 04 '12 at 13:27
  • As mKorbel as pointed out, `KeyListeners` are not your best friend. In you case (and without knowing more), I'd be suggesting the use of [key bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer Sep 04 '12 at 20:10

3 Answers3

3

There is a method on the java.awt.event.KeyEvent just for your purpose - isControlDown()

kostja
  • 60,521
  • 48
  • 179
  • 224
3
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • It very much depends on what you're trying to do. E.g. the core of the example in the question, performing some action the moment Ctrl is pressed, isn't available through these interfaces. And there *might* be reasons to do such a thing. – MvG Sep 04 '12 at 14:54
  • @MvG I miss reason, doesn't make me sence listening for SHIFT or CTRL is pressed, because JTextComponents aren't designated for that, but nobody know real idea ..., out of upvotes ... – mKorbel Sep 04 '12 at 19:24
3

Don't use getKeyChar in combination with those VK_ constants. Use getKeyCode instead. getKeyChar is for printable keys only, which result in a character being printed in normal operations. getKeyCode, on the other hand, is intended to give you the code (i.e. the VK_ constant) of the key pressed, even if there is no associated character (as in the case of Ctrl).

See also this answer.

Community
  • 1
  • 1
MvG
  • 57,380
  • 22
  • 148
  • 276