开发者

Poll for pressed buttons in Java

I have a WorldWind application build based on the Java SDK. It has a great event handler for detecting when you click 开发者_Python百科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?


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
  } 
}


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(..);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜