Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Can we detect if a key is pressed without using a Listener?

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

like image 288
BrianHobbs Avatar asked Aug 25 '10 14:08

BrianHobbs


People also ask

How do you check if a key has been pressed in Java?

Use KeyEvent. getKeyChar() and KeyEvent. getKeyCode() to find out which key the user pressed.

How do I check if the user is pressing a key?

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 .

What does KeyTyped do in Java?

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.

What is the difference between KeyTyped and keyPressed Java?

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.


1 Answers

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.

like image 54
Erick Robertson Avatar answered Oct 05 '22 13:10

Erick Robertson