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();
Run Code Online (Sandbox Code Playgroud)
此方法工作正常,并将面板及其内容调整为正确的尺寸(并以简单的方式回答我的问题:“如何找到首选尺寸?getPreferredSize()”)。
但是,它需要将初始大小设置为足够大的大小,以便内容适合,否则它们将不会放置在布局上。这有点可惜,而且不是真正的“干净”,但目前我找不到办法避免这种情况。
编辑:实际上,默认大小是不必要的,因为getPreferredSize()即使在调用之前也会返回正确的值doLayout()。因此,在调用布局方法之前,可以将面板设置为其适当的大小。