views:

34

answers:

2

I'm looking for the following behaviour in a JPanel Layout (Swing): basically it would arrange the components in a Vertical way, one bellow each other. When the components can't fit vertically in the container, it should add the next one in a new row. This would continue dinamically, adding new rows as needed.

It would look likes this, after adding 3 labels:

+--------------------------+
|  label1                  |
|  label2                  |
|  label3                  |
+--------------------------+

After adding: 2 more labels:

+--------------------------+
|  label1  label4          |
|  label2  label5          |
|  label3                  |
+--------------------------+

Finally, after adding 2 more labels it would look like this:

+--------------------------+
|  label1  label4  label7  |
|  label2  label5          |
|  label3  label6          |
+--------------------------+

Is this behaviour possible to achieve with one of the current Layouts? or should I create one myself? How would you solve this solution?

+1  A: 

Yes, it is possible. Try using MigLayout.

Here's a code snippet which illustrates the usage:

JPanel panel = new JPanel(new MigLayout("fill, flowY, wrap 4));
panel.add(new JLabel("row 1, column 1"));
panel.add(new JLabel("row 2, column 1"));
panel.add(new JLabel("row 3, column 1"));
panel.add(new JLabel("row 1, column 2")); // etc.
Boris Pavlović
Ok thanks, but I was hopping the Layout would manage the column automatically, so when it doesn' fit in one column, it would add the component to the next column.
Hectoret
Also, I checked your code and the class LC does not have a method wrap that takes a parameter:http://www.migcalendar.com/miglayout/javadoc/net/miginfocom/layout/LC.html#wrap()
Hectoret
It's the case here. Fourth label "row 1, column 2" is going to be added in the second column while first three will be in the first.
Boris Pavlović
Fixed, Layout Constraint creator LC doesn't support all constraint builders, i.e. wrap(int). You can use String version like the one here.
Boris Pavlović
A: 

Ok, solution found. Thanks to Boris, using MigLayout:

LC lc_Y = (new LC()).fill().flowY();
lc_Y.setWrapAfter(ITEMS_PER_COLUMN);
JPanel panel = new JPanel(new MigLayout(lc_Y));

Now, it would be perfect if there was no need to specify the amount of items per column. I mean, the Layout would try to fill vertically the container with as many items in the same row as possible.

Hectoret