Suraj and willcodejavaforfood put me on a good track.
Checking what is actually done in the pack() method, I see that it basically sets the current size to the one returned by getPreferredSize() .
From this, I managed to make such a solution:
// 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();
This method works correctly and adjusts the panel and its contents to the correct size (and answers my question in a simplified form: "How to find the preferred size? getPreferredSize() ").
However, this requires you to set the initial size to a size large enough for the content to enter, or they will not be placed in the layout. This is a little pathetic and not entirely “clean”, but so far I can’t find a way to avoid this.
Edit: Actually, the default size is not needed, because getPreferredSize() returns the correct value even before doLayout() called. Thus, the panel can be customized to the desired size before invoking the layout method.
source share