Java – explain gridbag weight to display pixels relationship/formula/conversion

I’ve been playing around with GridBagLayout and I can’t seem to figure out how many pixels I’m going to get with a particular weighting in the constraints.

For example, say I have a 1000 pixel contentPane with three JPanels in it, with weights (say, weighty) of 0.1, 0.1, 0.8.

My first hypothesis was that panel 1 and 2 would be 100 pixels each, and panel 3 would be 800. Turns out it wasn’t.

How can I get an exact number of pixels to expect with respect to the weighting?

This question asks sort of the same thing, but the answers, while helpful, don’t answer the question. :- /


Never mind, I think I found the answer here:

When more than one column has a non-zero weight, the excess space is 
distributed among the non-zero weight columns using the weight values. 
In particular, if the excess space is P pixels, and the column weights 
for column^i is weight^i, then column^i gets exactly 
(weight^i * P) / (sum-of-all-column-weights). For example, if column 1 
has weight 1 and column 2 has weight 2 and the excess space is 90 pixels, 
column 1 will get 30 extra pixels and column 2 will get 60 extra pixels. 
Rows with a non-zero weight behave in similar fashion.

Apparently the problem is extra space being added to the cells.

Leave a Reply

Your email address will not be published. Required fields are marked *