Java gridlayout with empty cells


I want to show the status of some files in a Java GUI. Each file has a label and a button, the colour of the button represents the status of the file and clicking performs various operations. All this is working, the problem is that they are not showing correctly. I want it to appear as

[Label 1] [File 1] [File 2] [Label 2]
[Label 3] [File 3] [File 4] [Label 4]

To do this I have made a panel with a GridLayout

 new JPanel(new GridLayout((list.size() + 1) /2,4,3,3));

This works unless there is an odd number of files. Then the grid resizes itself, for example with 3 files I will get a 2×3 grid so label 2 shows on the next line. If I check for an odd number and then add 2 new JPanels after all the other controls it shows correctly but I was wondering if there is a better way of doing this.


Best Solution

Looking at the JavaDoc for GridLayout.setColumns, it appears that not specifying the row count will cure your ills.

Sets the number of columns in this layout to the specified value. Setting the number of columns has no affect on the layout if the number of rows specified by a constructor or by the setRows method is non-zero. In that case, the number of columns displayed in the layout is determined by the total number of components and the number of rows specified. (my emphasis)

Try this:

new JPanel(new GridLayout(0,4,3,3));