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());
}
谢谢。
答案 0 :(得分:2)
preferredLayoutSize()
是Container
s的默认首选大小。也就是说,如果容器有布局管理器,Container.getPreferredSize()
将返回该值,除非它被覆盖以返回其他内容,或者已使用setPreferredSize()
指定了另一个值。
将其更改为
public Dimension preferredLayoutSize(Container parent) {
return new Dimension(parent.getWidth(), parent.getHeight());
}
意味着容器不会考虑内容,但会始终返回其当前大小。
答案 1 :(得分:1)
只需在IDE中按Method usage
热键......
com.sun.java.swing.plaf.motif - rt.jar
-MotifFileChooserUI
--getPreferredSize(JComponent)
-MotifPopupMenuUI
--getPreferredSize(JComponent)
com.sun.java.swing.plaf.windows - rt.jar
-WindowsFileChooserUI
--getPreferredSize(JComponent)
java.awt - rt.jar
-Container
--getPreferredSize() (2 matches)
--preferredSize()
javax.swing.plaf.basic - rt.jar
-BasicDesktopIconUI
--getPreferredSize(JComponent)
-BasicInternalFrameUI
--getPreferredSize(JComponent)
-BasicOptionPaneUI
--getPreferredSize(JComponent)
javax.swing.plaf.metal - rt.jar
-MetalFileChooserUI
--getPreferredSize(JComponent)