ict*_*991 3 java swing components coordinates
我试图获取组件的坐标,例如标签.我尝试了getBounds和getLocation,但是如果标签位于2个或更多面板上,它们就不会给出准确的坐标.除了getLocationOnScreen,有没有办法能够获得准确的组件坐标,即使它们在多个面板上?
如果你想要它相对于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).
| 归档时间: |
|
| 查看次数: |
1277 次 |
| 最近记录: |