问题描述
是否可以告诉JPanel将其大小设置为适合它包含的所有组件?像JFrame的 pack()
之类的东西。
Is it possible to tell JPanel to set its size to fit all components that it contains? Something like pack()
for JFrame.
编辑:使用preferredSize的技巧没有帮助。我有JSplitPane,其中一部分是带有许多标签的GridBagLayout(见截图)和标签相互重叠。
edit: The trick with preferredSize didn't help. I've got JSplitPane, where in one part there is GridBagLayout with many labels (see screenshot) and labels overlap each other.
推荐答案
在查看 pack()
的源代码后,我想出了:
After looking at the source code for pack()
, I came up with:
panel.setPreferredSize(panel.getPreferredSize());
这会强制面板根据其子组件的首选大小重新计算其首选大小。
This forces the panel to recalculate its preferred size based on the preferred sizes of its subcomponenents.
您可能需要或不必致电;在我的小例子中,它似乎没有区别,但Javadoc说:
You may or may not have to call validate()
afterward; in my tiny example, it seemed to make no difference, but the Javadoc says:
所以我想这取决于你为什么要重新包装你的 JPanel
。
So I guess it depends on why you're having to repack your JPanel
.
这篇关于内部组件的JPanel大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!