如何获得Swing组件的坐标,无论其父级是什么?

ict*_*991 3 java swing components coordinates

我试图获取组件的坐标,例如标签.我尝试了getBounds和getLocation,但是如果标签位于2个或更多面板上,它们就不会给出准确的坐标.除了getLocationOnScreen,有没有办法能够获得准确的组件坐标,即使它们在多个面板上?

dav*_*veb 5

如果你想要它相对于JFrame,那么你必须做这样的事情:

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);
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用内置解决方案SwingUtilities.convertPoint(comp, 0, 0, root).

  • 我不能和_that_争论!:-)编辑,很想要这个应该提出一个问题的需要. (2认同)