How returns XxxSize from JComponent(s) added to the JLabel

The default preferred size calculation is to use the layout manager to determine the preferred size of a component. This means the layout manager iterates through all the child components to determine the preferred size of each. For a JPanel, which is meant to be used as a Container this calculation is used.

However, for other Swing components, the getPreferredSize() method is always overridden to provide a reasonable size for the given component.

In the case of a JLabel, the preferred size calculation takes into account the text and the icon used. Since you didn’t provide either the preferred size is zero. Of course if you manually override this calculation by using the setPreferredSize() method then the component will have a preferred size.

So even though Swing allows you to add components to any component and use a layout manager to layout the child components, these child components are not used in the preferred size calculation.

This is not just a Nimbus issue.

Leave a Comment