Mouse coordinates relative to the frame

I am trying to draw polygons and want to be able to click on my frame to get MouseCoordinates, to quickly turn the mental image into x / y values.

I use

System.out.println("("+ MouseInfo.getPointerInfo().getLocation().x +", "+ MouseInfo.getPointerInfo().getLocation().y +")"); 

but it gives me the coordinates relative to my actual screen, and not my java window.

How to make the coordinates display relative to the Java window?

+6
source share
2 answers

I suppose you add MouseListener to your frame? Then you can just get the relative coordinates using MouseEvent.getPoint

 frame.addMouseListener(new MouseAdapter() { void mouseClicked(MouseEvent e) { System.out.println(e.getPoint()); } }); 
+4
source

You can convert screen and component coordinates using the SwingUtilties class

The convertPointFromScreen method will take the coordinate of the screen and convert it relative to the component that you provide.

+13
source

Source: https://habr.com/ru/post/900812/


All Articles