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?
Try using MouseEvent. getPoint . Show activity on this post. MouseEvent has methods getX() and getY() that return the position relative to the source component.
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.
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.
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:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With