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

BrianHobbs picture BrianHobbs · Aug 25, 2010 · Viewed 7.7k times · Source

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

Answer

Erick Robertson picture Erick Robertson · Aug 25, 2010

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.