【问题标题】:Getting coordinates of a component in java在java中获取组件的坐标
【发布时间】:2010-11-24 17:14:43
【问题描述】:

我有一个 JLayeredPane,在 JLayeredPane 里面是一个 JInternalFrame。我需要的是 JInternalFrame 中内容窗格的边界(x 位置、y 位置、宽度、高度)。边界需要与 JLayeredPane 相关。我的问题是边框、标题栏,我不确定 JInternalFrame 的其他内容是否会影响我的计算。差了几个像素。

这是我尝试计算它的方法。此代码在 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 );

我需要获取内部框架的内容窗格的位置。

【问题讨论】:

    标签: java swing coordinates


    【解决方案1】:

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

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

    SwingUtilities 有几种方法可以将坐标从一个参考系转换到另一个参考系。因此,为了补偿标题栏和框架,您可以这样做:

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

    【讨论】:

    • 非常酷。我知道有一种简单的方法可以做到这一点。这非常有效。
    【解决方案2】:

    JInternalFrame 的 getBounds() 方法返回一个带有您需要的坐标的 Rectangle。为什么不直接执行以下操作:

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

    这样你就不需要手动计算边界了。

    【讨论】:

    • 这个问题是这会给我包括内部框架的标题栏和边框的边界。我只需要内容窗格的边界。但我需要将 x 坐标和 y 坐标指向 JLayeredPane 中内容窗格的位置。
    猜你喜欢
    • 2011-09-27
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    相关资源
    最近更新 更多