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?
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With