在Java中获取组件的坐标 [英] Getting coordinates of a component in java

查看:355
本文介绍了在Java中获取组件的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JLayeredPane,在JLayeredPane内是一个JInternalFrame。我需要的是JInternalFrame中内容窗格的边界(x位置,y位置,宽度,高度)。范围必须与JLayeredPane有关。我的问题是边框和标题栏,而且我不确定JInternalFrame的其他内容是否会影响我的计算。距离它有几个像素。

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.

这是我尝试计算的方式。这段代码在JInternalFrame中:

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.

推荐答案

关于什么的坐标?屏幕?窗口?

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

调用 getLocation()将为您提供相对于窗口层次结构中组件父级的坐标。

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

SwingUtilities 具有几种将坐标从一个参考系转换到另一个参考系的方法。因此,为了补偿标题栏和边框,您可以执行以下操作:

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

这篇关于在Java中获取组件的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆