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

pipsqueaker117 picture pipsqueaker117 · Sep 12, 2012 · Viewed 96.1k times · Source

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 mouseX = MouseInfo.getPointerInfo().getLocation.x;

Seems to give the location of the mouse on the entire screen. How would I get it's location relative to the GUI?

Answer

David Kroukamp picture David Kroukamp · Sep 12, 2012

From MouseListener methods you can do:

@Override
public void mouseClicked(MouseEvent e) {
    int x=e.getX();
    int y=e.getY();
    System.out.println(x+","+y);//these co-ords are relative to the component
}

Simply add this to your Component by:

component.addMouseListener(new MouseListener() {
    @Override
    public void mouseClicked(MouseEvent e) {
    }
});

Reference: