L. Mehmeti
L. Mehmeti

Reputation: 34

How to make a component fit parents width using BoxLayout?

I have JPanel with BoxLayout Y-Axis and want to add multiple JLabels to this Panel. The Labels should fit the Panels width but only use the height they need to. Can one of you help me?

Upvotes: 0

Views: 2314

Answers (1)

camickr
camickr

Reputation: 324167

How to make a component fit parents width using BoxLayout?

A BoxLayout respects the maximum size size of a component. For a JLabel the preferred and maximum sizes are the same so the label doesn't grow in size.

So you could override the the getMaximumSize() method of each JLabel to do something like:

return new Dimension(getPreferredSize().width, Integer.MAX_VALUE);

However an easier approach is to nsting panels to ive you the effect you need.

For example:

JPanel labelPanel = new JPanel( new GridLayout(0, 1) );
labelPanel.add(new JLabel( "one" ) );
labelPanel.add(new JLabel( "two" ) );

JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(labelPanel, BorderLayout.PAGE_START);

frame.add(wrapper, BorderLayout.CENTER);

Now the labelPanel will take only the height it needs but the width will grow to fill the width of the frame and therefore the labels width will also grow.

Another option, without using nested panels is to use the GridBagLayout. It supports a fill constraint which will allow each component to resize to fill the space available.

Read the section from the Swing tutorial on Layout Managers for more information.

Upvotes: 3

Related Questions