开发者

Getting coordinates of a component in java

开发者 https://www.devze.com 2023-01-26 14:39 出处:网络
I have a JLayeredPane, and inside the JLayeredPane is a JInternalFrame. What I need are 开发者_JS百科the bounds (x position, y position, width, height) of the content pane in the JInternalFrame. The b

I have a JLayeredPane, and inside the JLayeredPane is a JInternalFrame. What I need are 开发者_JS百科the bounds (x position, y position, width, height) of the content pane in the JInternalFrame. The bounds need to be in relation to the JLayeredPane. My problem is the borders, title bar, and I'm not sure what else of the JInternalFrame are messing with my calculation. It's a few pixels off.

Here is how I try to calculate it. This code is in the JInternalFrame:


Rectangle area = new Rectangle(
                getX() + 2,  //The x coordinate of the JInternalFrame + 2 for the border
                getY() + ((javax.swing.plaf.basic.BasicInternalFrameUI) getUI()).getNorthPane().getHeight(), //The Y position of the JinternalFrame + theheight of the title bar of the JInternalFrame
                getContentPane().getWidth() - 2, //The width of the Jinternals content pane - the border of the frame
                getContentPane().getHeight() //the height of the JinternalFrames content pane
                );

I need to get the location of the content pane of the internal frame.

Getting coordinates of a component in java


Coordinates with respect to what? The screen? The window?

Calling getLocation() will give you the coordinates relative to the component's parent in the window hierarchy.

SwingUtilities has several methods for transforming coordinates from one frame of reference to another. So, to compensate for the title bar and frame, you can do this:

JInternalFrame iframe = ...
Container c = iframe.getContentPane();
Rectangle r = c.getBounds();
r = SwingUtilities.convertRectangle(c.getParent(), r, iframe.getParent());


The getBounds() method of JInternalFrame returns a Rectangle with the coordinates you need. Why not just do the following:

{
      ...
      JInternalFrame iframe = ...;
      Rectangle r = new Rectangle(iframe.getBounds());
}

This way you don't need to manually calculate the bounds.

0

精彩评论

暂无评论...
验证码 换一张
取 消