Weightx and Weighty in Java GridBagLayout
Asked Answered
S

2

26

I have some trouble understanding these two properties. How should I give weight to components? How are these numbers calculated? I have tried to read several articles on the web but I do not understand it.

Thank you.

Showalter answered 26/4, 2011 at 11:17 Comment(0)
S
26

If the space within a Panel is greater than the preferredDimension of the components contained within, the weightx and weighty is used to distribute the extra space to the individual components.

use values from 0.0 to 1.0 (think of this a percentage).

  • weightx is horizontal spacing

  • weighty is vertical spacing

The most common scenario in desktops is that the side panes stay a fixed size (weightx/weighty = 0.0) and the center pane takes up the remaining space (weightx/weighty = 1.0). however, using variations, you can have complete control of how your application resizes the individual components as the Frame size changes.

Seaquake answered 26/4, 2011 at 11:26 Comment(4)
Very good, but you don't have to use values from 0.0 to 1.0. Values can be anything. The extra space is allocated per the percentage of the individual components weight divided by the total weight of all components in the row or column.Gorgonzola
Indeed. I only suggested using between 0.0 and 1.0 because it is best practice, and it makes it easier to read the code if thinking in percentage terms.Seaquake
Thank you. So if two buttons have a weightx of 0.2 and 0.8 one of the button will get "20%" and the other one "80%" of the space?Showalter
@Andreas - absolutely yes. 80/20 split of the space over and above the preferredDimensions.Seaquake
C
2

weightx and weighty are used to determine how to distribute space among columns and among rows.

This values are important for specifying resizing behavior.If you do not specify any of weightx or weighty, all the components will clump together in the center of their container. See the doc of GridBagLayout for more information.

For each column, the weight is related to the highest weightx specified for a component within that column. Similarly, each row's weight is related to the highest weighty specified for a component within that row.

Chickweed answered 26/4, 2011 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.