【发布时间】:2013-08-08 12:37:52
【问题描述】:
所有java布局管理器都需要preferredLayoutSize(Container parent),但是这个方法什么时候调用呢?
以下代码在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());
}
谢谢。
【问题讨论】:
-
但是如果我把上面所有的代码都改成下面的会有什么不同呢?可能只有一个(第一个或最后一个)JComponent 将占据整个区域(来自容器),GridLayout 有行和列
-
System.out.printlninGridLayout.java?嗯...) -
@mKorbel 当我使用 GridLayout 时,我根本没有看到这个方法被调用。所以我想知道在什么情况下会调用这个方法。
-
打包、setPreferredSize、(重新)验证、调整容器大小
标签: java swing layout-manager preferredsize