views:

100

answers:

3

Hi There,

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

A: 

Even if there was such a method, what do you want to do with it? Call it in an endless loop in the hope it returns true at some point? I think an event-based / listener-based mechanism suits much better in this case.

Jeroen Rosenberg
DaddyB
+3  A: 

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.

Erick Robertson
DaddyB
DaddyB
I updated my response - you can check the MouseEvent being generated every time the mouse is moved or dragged.
Erick Robertson
A: 

I think you are going about this the wrong way. What you want to do is change the action when the drag is initiated, not when it is dropped. There are ways to change what the action is on initiation, including interrogating the user preferences in the "no modifiers" case. It's possible that changing the way the DropTargetDragEvent is called.

DJClayworth
I agree - but I've not been able to work out how to set the "no modifiers" case in code - the javadocs (see link in my original post) indicate that copy takes priority over link. If you've got any suggestions on how to do this then it would be much appreciated.
DaddyB