preferredLayoutSize(Container parent)
所有java布局管理器都需要,但是什么时候调用这个方法?
以下代码位于GridLayout.java
:
public Dimension preferredLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
System.out.println(parent.getWidth() + " " + parent.getHeight());
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int nrows = rows;
int ncols = cols;
if (nrows > 0) {
ncols = (ncomponents + nrows - 1) / nrows;
} else {
nrows = (ncomponents + ncols - 1) / ncols;
}
int w = 0;
int h = 0;
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = parent.getComponent(i);
Dimension d = comp.getPreferredSize();
if (w < d.width) {
w = d.width;
}
if (h < d.height) {
h = d.height;
}
}
return new Dimension(insets.left + insets.right + ncols*w + (ncols-1)*hgap,
insets.top + insets.bottom + nrows*h + (nrows-1)*vgap);
}
}
但是,如果我将上面的所有代码更改为以下代码,会有什么不同?
public Dimension preferredLayoutSize(Container parent) {
return new Dimension(parent.getWidth(), parent.getHeight());
}
谢谢你。