Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 342
ict1991 Avatar asked Dec 16 '22 01:12

ict1991


1 Answers

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

like image 100
daveb Avatar answered Feb 15 '23 23:02

daveb