How to get location of a mouse click relative to a swing window

后端 未结 4 1631
生来不讨喜
生来不讨喜 2020-11-27 20:54

Say I\'m in a Java Swing JFrame. I click my mouse. I want to get the location of the mouse click within the GUI. In java, the line

int mouse         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 21:37

    Take a look at Component.getMousePosition.

    Returns the position of the mouse pointer in this Component's coordinate space if the Component is directly under the mouse pointer, otherwise returns null. If the Component is not showing on the screen, this method returns null even if the mouse pointer is above the area where the Component would be displayed. If the Component is partially or fully obscured by other Components or native windows, this method returns a non-null value only if the mouse pointer is located above the unobscured part of the Component.

    final Point mousePos = component.getMousePosition();
    if (mousePos != null) {
      final int mouseX = mousePos.x;
      final int mouseY = mousePos.y;
      ...
    }
    

    ... or, if you use a MouseListener, you may see my original comment...

    Try using MouseEvent.getPoint.

    The above will return the mouse point relative to the component to which the listener was bound.

    public void mouseClicked(final MouseEvent evt) {
      final Point pos = evt.getPoint();
      final int x = pos.x;
      final int y = pos.y;
    }
    

提交回复
热议问题