Getting coordinates of a component in java

倾然丶 夕夏残阳落幕 提交于 2020-01-24 12:27:09

问题


I have a JLayeredPane, and inside the JLayeredPane is a JInternalFrame. What I need are 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.


回答1:


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());



回答2:


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.



来源:https://stackoverflow.com/questions/4269540/getting-coordinates-of-a-component-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!