How to align column data in vaadin flow Grid with .setTextAlign

Viewed 273

I have a grid and I would like to align the values according to class type like the non-working code below? Is there a way to have setTextAlign inside if statements?

Grid.Column<Record> firstNameColumn = grid
.addColumn(item -> {
    String value =  item.getColumnData(strSelectColumnNames[fc]);
    
            
        
        return item == null ? "-" : value;

       })
if(colClass.equalsIgnoreCase("java.lang.Double"))
{
 .setTextAlign(ColumnTextAlign.END)
}
else
{
 .setTextAlign(ColumnTextAlign.START)
}

.setWidth((colWidth-1)+"em")
.setHeader(strSelectColumnNames[fc]);
2 Answers

I just found the answer:

.setTextAlign(colClass.equalsIgnoreCase("java.lang.Double") ? ColumnTextAlign.END :ColumnTextAlign.START)

Another option would be to set the text align after the other configurations are done using the column reference you saved:

if (colClass.equalsIgnoreCase("java.lang.Double")) {
   firstNameColumn.setTextAlign(ColumnTextAlign.END);
} else {
   firstNameColumn.setTextAlign(ColumnTextAlign.START);
}

Your code was failing because each configuration call returns the column reference, so that you can queue several calls without needing to save the reference to a variable. When you added the if section in the middle you broke that queue without closing it with a ; or adding that column reference to the calls after the break.

Related