代码之家  ›  专栏  ›  技术社区  ›  user489041

在Java中获取组件的坐标

  •  2
  • user489041  · 技术社区  · 14 年前

    我有一个jlayeredpane,jlayeredpane内部是一个jinternalframe。我需要的是JinternalFrame中内容窗格的边界(X位置、Y位置、宽度、高度)。边界必须与jLayeredPane相关。我的问题是边界,标题栏,我不知道还有什么其他的金氏框架困扰我的计算。只有几个像素。

    下面是我计算它的方法。此代码位于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 回复  |  直到 14 年前
        1
  •  6
  •   Devon_C_Miller    14 年前

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

    打电话 getLocation() 将在窗口层次结构中为您提供与组件父级相关的坐标。

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

    JInternalFrame iframe = ...
    Container c = iframe.getContentPane();
    Rectangle r = c.getBounds();
    r = SwingUtilities.convertRectangle(c.getParent(), r, iframe.getParent());
    
        2
  •  2
  •   Carlo del Mundo    14 年前

    jinternalFrame的getBounds()方法返回一个具有所需坐标的矩形。为什么不做下面的事情呢?

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

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