Skip to content

Instantly share code, notes, and snippets.

@TatuLund
Last active June 18, 2024 06:48
Show Gist options
  • Save TatuLund/0706caee78a5ed43e63fd35573531967 to your computer and use it in GitHub Desktop.
Save TatuLund/0706caee78a5ed43e63fd35573531967 to your computer and use it in GitHub Desktop.
Vaadin 24 uses only a small fraction of the rows to autocalculate column widths, as it would be too slow otherwise. Your Grid may have long and short data scattered around in the Grid, hence the calculation based on the first rows may not be good for the whole Grid. Then it would be nice to recalculate the widths when Grid is being scrolled to n…
package com.example.application.views;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.router.Route;
@Route(value = "autowidth", layout = MainLayout.class)
public class GridColumnWidths extends Div {
private Integer index;
Grid<Integer> grid = new Grid<>();
public GridColumnWidths() {
var rand = new Random();
grid.setWidth("300px");
grid.addColumn(i -> i).setHeader("#").setAutoWidth(true);
grid.addColumn(i -> "Blaa blaa").setHeader("Blaa blaa")
.setAutoWidth(true);
grid.addColumn(i -> "Blaa").setHeader("Blaa").setAutoWidth(true);
grid.addColumn(i -> "Blaa a").setHeader("Blaa a").setAutoWidth(true);
grid.addColumn(i -> IntStream.rangeClosed(0, i).mapToObj(j -> "Bla")
.collect(Collectors.joining(" "))).setHeader("Random")
.setAutoWidth(true);
grid.addColumn(i -> "A Bla").setHeader("A Bla").setAutoWidth(true);
grid.addColumn(i -> "A Bla aa").setHeader("A Bla aa")
.setAutoWidth(true);
var items = IntStream.range(0, 20).mapToObj(i -> 1)
.collect(Collectors.toList());
items.addAll(IntStream.range(0, 1000).mapToObj(i -> rand.nextInt(7))
.collect(Collectors.toList()));
grid.setItems(items);
grid.getElement().executeJs("""
var scrollLeft = 0;
function debounce(func, wait) {
let timeout;
return () => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(func, wait);
}
}
const onScroll = debounce(() => {
if (scrollLeft == $0.$.table.scrollLeft) {
$0.recalculateColumnWidths();
}
scrollLeft = $0.$.table.scrollLeft;
}, 100);
$0.$.table.addEventListener('scroll', onScroll);
""",
grid.getElement());
add(grid);
setSizeFull();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment