Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 776
pipsqueaker117 Avatar asked Sep 12 '12 20:09

pipsqueaker117


People also ask

Which methods are used to get the location of mouse pointer in swing?

Try using MouseEvent. getPoint . Show activity on this post. MouseEvent has methods getX() and getY() that return the position relative to the source component.

How do you use a mouse motion listener?

Move the cursor into the yellow rectangle at the top of the window. You will see one or more mouse-moved events. Press and hold the mouse button, and then move the mouse so that the cursor is outside the yellow rectangle. You will see mouse-dragged events.

What is MouseListener in Java?

The mouse listener listens for events both on the BlankArea and on its container, an instance of MouseEventDemo . Each time a mouse event occurs, a descriptive message is displayed under the blank area. By moving the cursor on top of the blank area and occasionally pressing mouse buttons, you can fire mouse events.


2 Answers

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:

  • How to Write a Mouse Listener
like image 147
David Kroukamp Avatar answered Oct 21 '22 20:10

David Kroukamp


You can add MouseListener to GUI component whose top left pixel should be threated as [0,0] point, and get x and y from MouseEvent

JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
panel.addMouseListener(new MouseAdapter() {// provides empty implementation of all
                                           // MouseListener`s methods, allowing us to
                                           // override only those which interests us
    @Override //I override only one method for presentation
    public void mousePressed(MouseEvent e) {
        System.out.println(e.getX() + "," + e.getY());
    }
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
like image 43
Pshemo Avatar answered Oct 21 '22 20:10

Pshemo