Poll for pressed buttons in Java

自作多情 提交于 2019-12-11 10:06:15

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2624943/poll-for-pressed-buttons-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!