Find x, y Coordinates of Mouse Position Example

Find x, y Coordinates of Mouse Position Example

We have seen earlier to handle mouse events separately with MouseListener and MouseMotionListener and also both listeners in a single program.

In this Mouse Position Example also, both listeners are implemented but the task is to find the x and y coordinates where mouse action take place on the frame.

To find, the MouseEvent class defines two methods getX() and getY() that return x and y coordinates position of mouse action.

Let us see what Java API says about these methods

  • int getX(): Returns the horizontal x position of the event relative to the source component.
  • int getY(): Returns the vertical y position of the event relative to the source component.

In the following code, where the mouse action takes place displayed the type of action performed and x and y coordinates where the action took place. At the place of action, one bullet (filled circle) is also displayed. All this achieved with repaint() method.

Mouse Position Example

addMouseListener(this);
addMouseMotionListener(this);

Both listeners are registered with the component frame.

x = e.getX();
y = e.getY();
str = "Mouse Pressed";
repaint();

getX() and getY() methods of MouseEvent return the the x and y coordinates of mouse action. repaint() displays the all the data on the frame.


ima
Output screen when mouse clicked of Mouse Position Example

Leave a Reply

Your email address will not be published. Required fields are marked *