How can one get the coordinates of Swing components regardless of their parent?

I am trying to get the coordinates of a component like a label. I tried getBounds and getLocation, however they do not give exact coordinates if the label is on 2 or more panels. Aside from getLocationOnScreen, is there a way to get the exact coordinates of the components even if they are on more than 1 panel?

+3


source to share


3 answers


If you want it relative to the JFrame you will need 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)

.

+5


source


Try the component. getLocationOnScreen ()

As Javadok says,



Gets the location of this component, as a point that specifies the corner of the top-left component in screen coordinate space.

+3


source


+3


source







All Articles