Find X Y Coordinates Mouse Cursor Location

Find X Y Coordinates Mouse Cursor Location

A similar program is available in frame – Finding x and y Coordinates of Mouse Position. The same frame program is converted to applet. Following is the example. The mouse cursor location in x and y Coordinates and the type of action are displayed on the applet window and also on the applet status bar.

To locate the cursor, 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.

Two listeners MouseListener and MouseMotionListener are added to applet and overridden total 7 abstract methods.

HTML file to call the applet, AppletMouseXY.

Java Program, File Name: AppletMouseXY.java

addMouseListener(this);
addMouseMotionListener(this);

Two listeners MouseListener and MouseMotionListener are added to applet so that these two listener interfaces can handle the events generated by mouse on the applet window.

x = e.getX();
y = e.getY();

The getX() and getY() methods of MouseEvent returns the x and y coordinates of where the mouse action took place.

showStatus(str + ” at ” + x + “,” + y);

repaint() method calls implicitly paint() method. Calling paint() methods directly raises compilation error. Why?

showStatus(String message) of Applet class displays the message on the status bar of the applet window. See the output screen.

Output screen with x and y coordinates when mouse is moved.


Find X Y Coordinates Mouse Cursor Location
Output screen of Find X Y Coordinates Mouse Cursor Location

Leave a Reply

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