I am building a simple graphing application in Java, it requires me to get the mouse position within the 2D graphics canvas. I have used the code MouseInfo.getPointerInfo().getLocation()
, but it returns the mouse position relative to the JFrame window and not the g2d canvas.
For example, when my mouse cursor is at the coordinates (0,0) on the g2d canvas, MouseInfo.getPointerInfo().getLocation()
will return (8,30) because of the border around the window.
I could just factor in the offset, but window border size changes for each OS.
Would I need to manually check the OS and factor in the border offset, or is there a faster way?
The problem was solved using this post. I needed to use this approach:
Add the event listener:
myJFrame.getContentPane().addMouseListener(listener);
Get the mouse location within a mouse event function:
evt.getPoint()