Grid
Introduction
The Grid layout organizes components in cells. The advantage of using a Grid instead of a Table is that you can put any TUI component into it, when you must put strings into Table cells. But the way the sizes are managed is also a big difference from the Table layout.
You can put any component into a cell by using its coordinates (rowIndex, columnIndex). For example the coordinates of a grid 3x4 are:
Managing the sizes
By default every columns have the same width, and every rows have the same height. Both dimensions are determined by the biggest components. Here is an example with a 2x2 grid:
As you can see there is some room at the right and at the bottom of the components. This is because the Grid is set with a fixed width that is larger that what the components require. The same way, when a component has a height smaller that the height of its row, then some room appears at its bottom. The layout is computed as follow:
- Sizes of rows and columns are computed against the minimum sizes of their components.
- In each cell, the component is placed on the top left corner.
Displaying components in rows
The Grid layout may be used to display elements in harmonized rows.
In that example, we want to display a list of emails. The goal of the view is to show the dates and the subjects, and two action buttons for each email. Because we want the list to be displayed with well-aligned columns, we use a Grid layout. We set the columns width constraints: the first column will contain the dates and we want it compact, the second column will contain the subjects and we want it as wide as possible, the third column will contain the buttons and we want it compact.
Grid grid = new Grid(emails.size(), 3);
grid.setColumnWidthMaxContent(0);
grid.setColumnWidthAuto(1);
grid.setColumnWidthMaxContent(2);
First challenge: we want to vertically align the elements of a same row.
To do that, each element added into a cell is put into a Panel using VERTICAL_CENTER. An other challenge is to get the dates strings not wrapped on two lines. This is achieved using 'disableTextWrap':
Panel result = new Panel(Panel.Align.VERTICAL_CENTER);
Paragraph.Text text = result.append(new Paragraph.Text(date));
text.customStyle().setBackgroundColor(Color.LIGHT_GRAY)
text.customStyle().setBorderRadius_px(2)
text.customStyle().setPadding(1, 5, 1, 5);
text.customTextStyle().setTextSize_em(0.8f)
text.customTextStyle().disableTextWrap();
You can find the complete code in the Java source of this page in class TUIDocsGrids which produces with 10 randomized emails: