I need to be able to detect if a certain key (e.g. CTRL) is pressed during a specific operation of mine. I don't have access to a key listener, nor to a mouse event. What I'm hoping is that there will be some class that has a method like "boolean isKeyPressed(keycode)".
Is anyone aware of a method like this in java?
For a bit of background, I am trying to override the default drag & drop behaviour for a component. By default, according to the javadocs for DropTargetDragEvent, if no key modifier is pressed, then the it looks in the component's supported actions list for a move, then a copy & then a link and stops after finding the first one.
In my application, we support both copy & link. As per the javadoc, without the CTRL key pressed, the default action is copy. We want the user to be able to specify the default action (allowing them to set their most commonly used) and then force a specific one using the modifier keys.
If I can detect the key pressed state then I can force this to happen but I can't see any other way of changing the default action.
Thanks in advance, Brian
Use KeyEvent. getKeyChar() and KeyEvent. getKeyCode() to find out which key the user pressed.
Then you can always use: if (IsKeyPressed. isWPressed()) { // do your thing. } You can, of course, use same method to implement isPressing("<some key>") with a map of keys and their state wrapped inside IsKeyPressed .
The KeyTyped() listener method is called when a character is typed, but is not useful for virtual keys (arrow keys, function keys, etc). Modifier key (shift, control, etc) status (up/down) can be tested with method calls in the listener. These methods are called whenever any key is pressed or released.
The keyPressed method is called when the user presses a key, the keyReleased method is called when the user releases a key, and the keyTyped method is called when the user types a character.
The MouseEvent.getModifiers()
method will return a bitmap of modifier keys that are pressed at the time the MouseEvent
was generated. Or, you could use MouseEvent.isControlDown()
to check specifically the CTRL key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With