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

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:

Leave a Comment