Mouse coordinates relative to Frame
15,601
Solution 1
I suppose you add a MouseListener to your frame? Then you can just get the relative coordinates with MouseEvent.getPoint
frame.addMouseListener(new MouseAdapter() {
void mouseClicked(MouseEvent e) {
System.out.println(e.getPoint());
}
});
Solution 2
You can convert between screen and component coordinates using the SwingUtilties class
The method convertPointFromScreen will take a screen coordinate and convert it to be relative to the component you provide.
Author by
Admin
Updated on July 06, 2022Comments
-
Admin over 1 year
I'm trying to draw Polygons and would like to be able to click on my Frame to get MouseCoordinates so as to turn a mental Image into x/y values more quickly.
I'm using
System.out.println("("+ MouseInfo.getPointerInfo().getLocation().x +", "+ MouseInfo.getPointerInfo().getLocation().y +")");
but this give me coordinates relative to my actual screen, and not my java window.
How can I make the coordinates show up relative to the Java Window?
-
Admin over 12 yearsIt works, but it's not giving me the correct coordinates. To test it out I drew a square at x=50 and 7=50(g.drawRect(50,50,100,100)); and when I clicked the top left corner of the square, it save me x=58 and y=78 (java.awt.Point[x=58;y=78])
-
SpiderPig over 12 yearsThat's because you get the mouse coordinates relative to the JFrame but you don't paint directly on the frame. You probably paint on a JPanel that you added to the JFrame. That means you have to add the MouseListener to that JPanel to get the right coordinates.
-
Admin over 12 yearsmy bad, I got frame and panel confused, it's fixed now