有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing在java中获取组件的坐标

我有一个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
                );

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


共 (2) 个答案

  1. # 1 楼答案

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

    调用getLocation()将给出相对于窗口层次结构中组件父级的坐标

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

    JInternalFrame iframe = ...
    Container c = iframe.getContentPane();
    Rectangle r = c.getBounds();
    r = SwingUtilities.convertRectangle(c.getParent(), r, iframe.getParent());
    
  2. # 2 楼答案

    JInternalFrame的getBounds()方法返回一个带有所需坐标的矩形。为什么不做以下事情:

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

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