Suraj 和 willcodejavaforfood 让我走上了正轨。
检查方法中实际做了什么pack()
,我发现这主要是将当前大小设置为getPreferredSize()
.
由此,我设法做出了这样的解决方案:
// Creating the panel
JPanel lPanel = new JPanel();
//lPanel.setSize(1000, 1000); //default size, not needed anymore
lPanel.setLayout(new BoxLayout(lPanel, BoxLayout.PAGE_AXIS));
//Adding the content
lPanel.add(new JLabel("Blah"));
// etc...
//Adjust the panel to its preferred size
lPanel.setSize(lPanel.getPreferredSize());
//Call the layout method
//(this will adjust the content components to their correct size and position)
lPanel.doLayout();
此方法可以正常工作,并将面板及其内容调整为正确的大小(并以简单的方式回答我的问题:“如何找到首选大小?getPreferredSize()
”)。
但是,它需要将初始大小设置为足够大的大小,以便内容适合,否则它们将不会放在布局上。这有点可惜,并不是真正的“干净”,但我现在找不到避免这种情况的方法。
编辑:实际上,默认大小不是必需的,因为getPreferredSize()
即使在调用doLayout()
. 因此,可以在调用布局方法之前将面板设置为适当的大小。