File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Discrepancy between getX()/getY() & graphics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Discrepancy between getX()/getY() & graphics" Watch "Discrepancy between getX()/getY() & graphics" New topic

Discrepancy between getX()/getY() & graphics

Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
I am working with graphics in a JFrame. Within a graphics context, I drew a box in the vicinity of 325, 50. I want to check for mouse clicks in this box. I click on the center of the box. I would expect the MouseEvent's getX() and getY() methods to return 325 and 50, but instead they return 329 and 73!
It looks like when it comes to getX() and getY() in JFrames, at least, Java adds on the pixels at the left of the JFrame (there are only three or four) and at the top of the JFrame (the ones that make up the title bar). Are there any methods I could call to find out where the mouse is clicked that uses the same coordinate system as, say, drawRect() or drawLine()?
Thanks, as always.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
If you nest a JPanel inside your JFrame you will get a more predictable result.
Grant Crofton
Ranch Hand

Joined: Nov 08, 2000
Posts: 154
You can also find how many pixels it will be out by using Insets, something like this:

I agree. Here's the link:
subject: Discrepancy between getX()/getY() & graphics
It's not a secret anymore!