How is it possible to get the coordinates of a Swing components, irrespective to its parent?

components, coordinates, java, swing

Solution

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)`.

Problem

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?

Original source

Related problems