I am trying to get the coordinates of a component, for example a label. I tried getBounds, and getLocation, however they do not give accurate coordinates if the label is on 2 or more panels. Besides getLocationOnScreen, is there a way to be able to get accurate components' coordinates, even though they are on more than 1 panel?
Asked
Active
Viewed 1,566 times
4
-
How can a label be on more than one panel? – trashgod Apr 09 '12 at 08:49
-
what I mean is, you have more than one panel layered on each other, each containing their components, and the label is not directly on the primary panel – ict1991 Apr 09 '12 at 08:50
-
Ah, you mean in more than one (nested) `Container`. What's wrong with `getLocationOnScreen()`? – trashgod Apr 09 '12 at 08:54
-
yes your right sorry, for some reason it is still not giving me accurate location, especially when I maximize the frame – ict1991 Apr 09 '12 at 08:56
-
the x and y coordinate returned are being 8 and 29 units respectively more then they actually are, so I have to stay decreasing these values. When I maximize the windows, the difference would be bigger – ict1991 Apr 09 '12 at 09:05
-
1I am unable to reproduce this. It may help to edit your question to include an [sscce](http://sscce.org/) that exhibits the problem you describe. – trashgod Apr 09 '12 at 09:09
-
1*"I am trying to get the coordinates of a component,.."* Why exactly? What program feature does that support? – Andrew Thompson Apr 09 '12 at 09:12
3 Answers
6
If you want it relative to a JFrame, then you'll have to do something like this:
public static Point getPositionRelativeTo(Component root, Component comp) {
if (comp.equals(root)) { return new Point(0,0); }
Point pos = comp.getLocation();
Point parentOff = getPositionRelativeTo(root, comp.getParent());
return new Point(pos.x + parentOff.x, pos.y + parentOff.y);
}
Or you can just use the built-in solution SwingUtilities.convertPoint(comp, 0, 0, root)
.

fredoverflow
- 256,549
- 94
- 388
- 662

daveb
- 74,111
- 6
- 45
- 51
-
2I can't argue with _that_! :-) Edit, well wanting this should make one question the need. – trashgod Apr 09 '12 at 09:23
3
Try Component.getLocationOnScreen()
As the Javadoc says,
Gets the location of this component in the form of a point specifying the component's top-left corner in the screen's coordinate space.

COD3BOY
- 11,964
- 1
- 38
- 56
-
@AndrewThompson Thank you :) It took me almost a month for the last 100 reps! #LazyTheseDays :D – COD3BOY Apr 09 '12 at 09:45
-
No stress, we all give what time we can. No obligations (& no regrets). – Andrew Thompson Apr 09 '12 at 09:58
-
@AndrewThompson Thats it! :) and I'm waiting to wish you on the 50K milestone :) – COD3BOY Apr 09 '12 at 10:03
3
As an alternative to getLocationOnScreen()
, you may be able to use getXOnScreen()
and getYOnScreen()
from a MouseEvent
. Zoom
is an example.