1
votes

I have a container that has within it some unknown number of components (which are actually also containers in which I have overridden calcPreferredSize to make them a consistent size). Since the number of components may be > the number that can fit on a single line, there may be an overflow to line 2, etc.

I am using FlowLayout on the outer container, which works fine for one row. But the second row is offset.

So where I want:

|.X.X.X.|
|.X.X.X.|

I actually get:

|.X.X.X.|
|X.X.X..|

where X is the component, dots are spacing, and | are the sides of the container.

What is the best way to do this? I assume FlowLayout does this because the left margin for the first element on row 2 is actually applied on the top row, so there is no margin remaining to push it away from the container border.

I have tried GridLayout, but I find the rightmost X component on each row is expanded beyond the preferred size I have set.

2

2 Answers

0
votes

Row spanning is the problem here. If you override calcPreferredSize you're effectively blocking the spanning from working properly as we need to allocate space for each component horizontally and vertically.

The problem is that layout is determined and then line breaks might need more space (vertically) but layout was already set. The only solution for this is reflow (or multiple-passes) which we don't "really" support as it includes a serious performance overhead.

Grid layout will set everything to the same size. A table layout might be a better choice. I suggest not overriding calcPreferredSize() and instead just using 50% as the width of the table columns.

0
votes

I resolved this by putting padding on the left side and top of the container, and then changing the component margin so that the margin is on the right and bottom, rather than the top and left. This allows me to use FlowLayout on the container which is preferable as it does not alter the preferred size of the components in it.

So when flow layout puts a component on row 2, the container padding forces the component away from the "wall".

Padding and margin is like a puzzle...but there is usually a way to use it to get the look you want - I just had to do some thinking to get this right.