why doesn’t size and preferredsize make this label bigger?

Not 100% why the label is only sized to the text and not the (hard coded) preferred size. I have not been able to duplicate this behaviour using other combinations of panels and layout managers.

You are using pack so all components should be sized to their preferred sizes.

  Dimension defaultLabelSize = new Dimension(150,150);      // was expecting this to enlarge the label.
  currentImageLabel.setPreferredSize(defaultLabelSize);
  currentImageLabel.setSize(defaultLabelSize);

A few comments:

  1. Setting the size will never work. The layout manager will always override the size/location based on the rules of the layout manager.

  2. The layout manager can use (or ignore) the preferred, minimum and maximum sizes of a component. In the case of the BoxLayout is does attempt to use the preferred size but will respect the minimum and maximum sizes (depending on the available space in the parent panel).

What do I need to do to fix the size of currentImageLabel?

So, to achieve your desired goal of a fixed preferred size for the JLabel you can use:

Dimension defaultLabelSize = new Dimension(150,150);      // was expecting this to enlarge the label.
currentImageLabel.setPreferredSize(defaultLabelSize);
currentImageLabel.setMinimumSize(defaultLabelSize);
currentImageLabel.setMaximumSize(defaultLabelSize);
//currentImageLabel.setSize(defaultLabelSize);

Edit:

was looking for why this doesn’t seem to work

For further clarification, change your original code to:

  currentImageLabel.setPreferredSize(defaultLabelSize);
  System.out.println(currentImageLabel.getPreferredSize());
  System.out.println(currentImageLabel.getMinimumSize());
  System.out.println(currentImageLabel.getMaximumSize());

You will see the min/max sizes of the label are not affected.

From point 2 above you will see that the BoxLayout is respecting the maximum size.

Therefore, by also overriding the maximum size, you allow the label to be displayed at is preferred size.

However, when you calculate the preferred size of the “currentImagePanel” the ( hardcoded) preferred size of the label is used in the preferred size calculation of the panel, so that panel is displayed at the preferred size.

Another note. The “leftContainingPanel” is not needed. You can just add the “leftPanel” to the BorderLayout.WEST, since the BorderLayout will respect the width of the component you add.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top