我是 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();
}
}
最佳答案
Upon calling this however, the value is 0.
创建组件时,组件的大小(和位置)默认为 0。
When I run the GUI however, I see DTPicture objects spanning vertically
布局管理器负责确定组件的大小/位置。但是,仅当您在框架上使用 pack()
或 setVisible(true)
时,才会调用布局管理器。
如果将组件添加到可见框架,则必须使用 revalidate() 方法来调用布局管理器。
想一想,布局管理器在所有组件都添加到面板之前无法完成其工作,因为它不知道如何调整每个组件的大小。特别是在 GridLayout 的情况下,所有组件的大小都与最大组件的大小相同。那么,在添加所有组件之前,如何知道最大的组件是什么?每次添加组件时都进行布局效率不高。
关于java - 添加 JComponent 后 getY() 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24943737/