Way2Java

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

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
import java.awt.*;
import java.awt.event.*;
public class MouseXY extends Frame implements MouseListener, MouseMotionListener
{
  int x, y;
  String str="";
  public MouseXY()
  {
    addMouseListener(this);
    addMouseMotionListener(this);

    setSize(300, 300);
    setVisible(true);
  }
                          // override MouseListener five abstract methods
  public void mousePressed(MouseEvent e)
  {
    x = e.getX();
    y = e.getY();
    str = "Mouse Pressed";
    repaint();
  }
  public void mouseReleased(MouseEvent e)
  {
    x = e.getX();
    y = e.getY();
    str = "Mouse Released";
    repaint();
  }
  public void mouseClicked(MouseEvent e)
  {
    x = e.getX();
    y = e.getY();
    str = "Mouse Clicked";
    repaint();
  }
  public void mouseEntered(MouseEvent e)
  {
    x = e.getX();
    y = e.getY();
    str = "Mouse Entered";
    repaint();
  }
  public void mouseExited(MouseEvent e)
  {
    x = e.getX();
    y = e.getY();
    str = "Mouse Exited";
    repaint();
  }
                          // override MouseMotionListener two abstract methods
  public void mouseMoved(MouseEvent e)
  {
    x = e.getX();
    y = e.getY();
    str = "Mouse Moved";
    repaint();
  }
  public void mouseDragged(MouseEvent e)
  {
    x = e.getX();
    y = e.getY();
    str = "Mouse dragged";
    repaint();
  }
  public void paint(Graphics g)
  {
    g.setFont(new Font("Monospaced", Font.BOLD, 20));
    g.fillOval(x, y, 10, 10);                 // gives the bullet
    g.drawString(x + "," + y,  x+10, y -10);  // displays the x and y position
    g.drawString(str, x+10, y+20);            // displays the action performed
  }
  public static void main(String args[])
  {
    new MouseXY();
  }
}

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.



Output screen when mouse clicked of Mouse Position Example