Search code examples
javaswingmouseeventmousemotionevent

How to find the mouse position relative to a panel constantly?


I'm using MouseListeners and I want it to tell me the mouse position without th mouse being clicked or held down. So I know where it is hovering over. How do I do this?

I have code such as this, to find the position when it is pressed but i'm unsure how to find the position all the time.

  public void mousePressed(MouseEvent me) {
    print("Mouse Pressed");
      xPosClicked = me.getX() ;
      yPosClicked = me.getY() ;
      print("(" + xPos + "," + yPos + ")");
  }

Solution

  • Use a MouseMotionListener to listen for movement: http://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html