tags:

views:

60

answers:

2

I have a WorldWind application build based on the Java SDK. It has a great event handler for detecting when you click on objects, but I've run into a snag. While I can click on and select individual objects, I can't determine if the user is pressing the control key while they click (if they want to select multiple objects). I can implement event handlers for both the mouse and the keyboard, but I can't for the life of me figure out how to tie the two together. How could I make my mouse listener poll the system for a list of currently depressed keys?

+4  A: 

You can call getModifiers() and bitwise compare to see if the control key (or shift key was depressed during the event.

public void mouseClicked( MouseEvent e ) {
  if( ( e.getModifiers() & ActionEvent.CTRL_MASK ) > 0 ) {
     // Control key depressed
  } 
}
staticman
You have beaten me, and with actual code. +1
Michael Myers
+1  A: 

For a MouseEvent , you could just call the getModifiers() to get a mask of modifier keys(shift/control/alt etc.) keys that are pressed .

For the general case, use a variable to tie them together ?

Your keyhandler sets/clears the variable when it registers a keypress, your mouselistener checks that variable.

If you need to decople these a bit more, just create a instance that both your key listener and mouselistener accesses.

public class Pressedkeys {
  private boolean shiftPressed = false;
  private boolean controlPressed = false;
  public void setShiftPressed(boolean pressed) {
    this.shiftPressed = pressed;
  }
  public void setControlPressed (boolean pressed) {
    this.shiftPressed = pressed;
  }
 public boolean isControlPresed() {
   return controlPressed ;
  }
  ...
}

Pressedkeys k = new PressedKeys();
MyMouseThing t = new MyMouseThing(k);
//your mousething mouse handler would check k.isControlPressed();
MyKeyboardThing t = new MyKeyboardThing (k);
//your KeyBoardThing - which has a key handler would set k.setControlPressed(..);
leeeroy