Skip to content
Advertisement

GridBagLayout 25% 50% 25%

Is this the right way to prevent GridBagLayout cells from being resized relative to their contents?

JavaScript

enter image description here

SSCCE

JavaScript

Advertisement

Answer

Interesting. I’ve never seen an approach like this before.

Typically the GridBagLayout is used such that:

  1. Each component is allocated space based on its preferred size
  2. If extra space is available then space is allocated to to each component based on the weightx (weighty) values assigned to each component.

Therefore only the extra space is allocated in the 25% 50% 25% ratio.

Your approach seems to ignore the preferred size of components and allocate space in the 25% 50% 25% ratio.

However, you would first need to make the following change to get the proper ratio:

JavaScript

Below is the simplified code I used to test allocating space to components on a panel that is 400 pixels wide:

JavaScript

And the results are:

JavaScript

So I would say the approach works.

Note: In case you are interested, in the past I have suggested you can use the Relative Layout which was designed specifically for this type of layout and is easier to use.

Using the RelativeLayout the above behaviour would be replicated by using:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement