How to center a HeaderRow in Vaadin 14?

Viewed 90

I've got a HeaderRow grouping a Name and Status column. The HeaderRow is named User and is currently positioned to the very left of a Grid. This is what it looks like now:

        | User |
        | Name | |Status|

I would like the User header to be centered, like so:

             | User |
        | Name | |Status|

My current code. Keep in mind that the statusLabel and resourceLink methods are irrelevant to the problem.

public Grid<E> loadGrid(Class<? extends Resource> res) {
        try {
            Grid<E> grid = new Grid<>();
            Column<E> nameColumn = grid.addComponentColumn(E -> resourceLink(E)).setHeader("Name").setWidth("50%")
                    .setFlexGrow(0).setTextAlign(ColumnTextAlign.CENTER);
            Column<E> statusColumn = grid.addComponentColumn(E -> statusLabel(E)).setHeader("Status").setWidth("50%")
                    .setFlexGrow(0).setTextAlign(ColumnTextAlign.CENTER);
            grid.addClassName("availaboard-grid");
            grid.setAllRowsVisible(true);
            grid.setItems((Collection<E>) (db.loadResources(type)));

            grid.addSelectionListener(selection -> {
                grid.getSelectionModel().getFirstSelectedItem().ifPresent(item -> {
                    System.out.println(item.getName());
                });
            });
            
            HeaderRow headerRow = grid.prependHeaderRow();
            headerRow.join(nameColumn, statusColumn).setText(res.getSimpleName());
        
            
            
            return grid;
        } catch (IllegalArgumentException | SecurityException e) {

        }
        return null;

    }

Thanks!

1 Answers

Instead of using setText you could use setComponent and add a component to the joined columns header and then, you can easily style that component. Something like this:

Div simpleNameCell = new Div();
simpleNameCell.setText(res.getSimpleName());
simpleNameCell.getElement().getStyle().set("text-align", "center");
headerRow.join(nameColumn, statusColumn).setComponent(simpleNameCell);
Related