JComponent: Getting the top left x,y coordinates
Hi,
I need to get the x and y coordinate of the top left corner of my JComponent, i.e. the top left coordinates of the window itself.
I need this because I am using the javax.swing.Popup class which uses screen coordinates...
I tried getBounds() and getLocation() without success.
Thanks!
[319 byte] By [
SFLa] at [2007-11-27 3:50:17]

# 1
> I need this because I am using the javax.swing.Popup
> class which uses screen coordinates...
>
> I tried getBounds() and getLocation() without
> success.
Those methods are the only I know of that return the coordinates of a Component. They return the coordinates relative to the coordinate space of the Component's parent. A (J)Frame should return it's coordinates relative to the top left screen corner, i.e. exactly what you want.
So basically, you need to traverse all the container hierarchy up to the Frame and recursively add the coordinates of the parent to your own. When you're done, you have screen coordinates.
HTH,
Mike
# 2
> So basically, you need to traverse all the
> container hierarchy up to the Frame and recursively
> add the coordinates of the parent to your own.
Actually, this is exactly what the Component class does when resizing/moving heavyweight components that have native peers (lightweight components are laid out by their direct parents in their own coord space, so no traversal is needed).
Example:
private void reshapeNativePeer(int x, int y, int width, int height, int op) {
// native peer might be offset by more than direct
// parent since parent might be lightweight.
int nativeX = x;
int nativeY = y;
for (Component c = parent;
(c != null) && (c.peer instanceof LightweightPeer);
c = c.parent)
{
nativeX += c.x;
nativeY += c.y;
}
peer.setBounds(nativeX, nativeY, width, height, op);
}