3

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Syd Lambert
  • 1,415
  • 14
  • 16
  • 1
    [This post](http://stackoverflow.com/questions/12465003/java-mouseevent-position-is-inaccurate) looks like a good one to solve your problem. – Frank Bryce Jul 20 '15 at 16:23
  • 1
    Thanks, John! The update in that post solved my problem completely. I needed to add a frame using this code: `frame.getContentPane().addMouseListener(listener);`, and then get the mouse location in the event listener with `evt.getPoint()` – Syd Lambert Jul 20 '15 at 17:00

1 Answers1

1

The problem was solved using this post. I needed to use this approach:

  1. Add the event listener:

    myJFrame.getContentPane().addMouseListener(listener);
    
  2. Get the mouse location within a mouse event function:

    evt.getPoint()
    
Community
  • 1
  • 1
Syd Lambert
  • 1,415
  • 14
  • 16