java – JPanel大小由内部组件

是否可以告诉JPanel将其大小设置为适合其包含的所有组件?像JFrame的pack()类似的东西.

编辑:preferredSize的技巧没有帮助.我有JSplitPane,其中有一部分是GridBagLayout与许多标签(见截图)和标签相互重叠.

screenshot http://foto.darth.cz/pictures/screen.png

看了一下pack()的源代码后,我想出了:

    panel.setPreferredSize(panel.getPreferredSize());

这迫使面板根据其子组件的优选尺寸重新计算其优选尺寸.

您可能会也可能不需要再打电话给validate();在我的小例子中,似乎没有任何区别,但Javadoc说:

The validate method is used to cause a container to lay out its subcomponents again. It should be invoked when this container’s subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.

所以我想这取决于你为什么要重新包装你的JPanel.

翻译自:https://stackoverflow.com/questions/849684/jpanel-size-by-inner-components

转载注明原文:java – JPanel大小由内部组件