getY()在添加JComponent时返回0

时间:2014-07-24 20:52:05

标签: java swing drag-and-drop

我是Swing的新手,所以我读了Java教程和API。我一直在玩JComponent的子类(DTPicture - 支持拖放)。基本上我创建了一个GridLayout的面板。然后我用DTPicture个对象填充面板。 DTPicture已继承getLocation()。然而,在调用它时,值为0.然而,当我运行GUI时,我看到DTPicture个对象垂直跨越。那么为什么getLocation会返回0?

感谢。

以下是我的代码: *其他所有内容都已初始化,声明和实施。

public class RackBuilderTool extends JPanel{
    //maps rack slot # to DTPicture location on JPanel
    public static Point[] slotIDArray = new Point[42];

    public RackBuilderTool() {
    super(new GridLayout(42, 1));

       //DTPicture[] rackSlotArray = new DTPicture[42];
       for (int i = 0; i < 42; i++) {
            //add(new ComponentLabel());
           DTPicture temp = new DTPicture(null);
           System.out.println(add(temp).getLocation());
           //address of DTPicture Component
           slotIDArray[i] = temp.getLocation();

       }
   }

1 个答案:

答案 0 :(得分:4)

  

然而,在调用它时,值为0.

创建组件时,组件的大小(和位置)默认为0.

  

然而,当我运行GUI时,我看到垂直跨越的DTPicture对象

布局管理器负责确定组件的大小/位置。但是,只有在框架上使用pack()setVisible(true)时才会调用布局管理器。

如果将组件添加到可见框架,则必须使用revalidate()方法来调用布局管理器。

考虑一下,在将所有组件添加到面板之前,布局管理器无法完成其工作,因为它不知道如何调整每个组件的大小。特别是在GridLayout的情况下,所有组件的大小与最大组件的大小相同。那么在添加所有组件之前,您如何知道最大的组件是什么?每次添加组件时进行布局都不是非常有效。