Vaadin addComponentColumn 仅适用于最后一行

Vaadin addComponentColumn only works in last row

    this.grid = new Grid<>(Person.class);
    this.grid.setItems(personList);
    this.grid.setSelectionMode(SelectionMode.MULTI);
    this.grid.removeAllColumns();
    this.grid.setColumns("firstname");
    this.editButton = new Button(null, ImageIcons.EDIT.create());
    this.editButton.getStyle().set("color", "#000000");
    this.grid.addComponentColumn(person -> this.editButton);
    this.deleteButton = new Button(null, IronIcons.DELETE_FOREVER.create());
    this.deleteButton.getStyle().set("color", "#000000");
    this.grid.addComponentColumn(person -> this.deleteButton);
    this.addComponentAsFirst(this.grid);

我有一个包含多个条目的 personList。网格显示所有这些条目及其名字。但它只显示最后一行的按钮。有什么问题?

您为每一行使用了完全相同的 Button 实例。您应该在 componentRenderer 中创建一个新的 Button,这样每一行都会有自己的 Button。

这样试试:

this.grid = new Grid<>(Person.class, false);
this.grid.setItems(personList);
this.grid.setSelectionMode(SelectionMode.MULTI);
this.grid.setColumns("firstname");

this.grid.addComponentColumn(person -> {
    // edit: added click listener for inline-editing of the person. Editor must be configured for this to work. See https://vaadin.com/components/vaadin-grid/java-examples/grid-editor
    // You don't have to use inline-editing if you don't want. you can also edit the item in a separate Layout with Input fields and a Binder.    
    Button editButton = new Button(ImageIcons.EDIT.create(), click -> {
        this.grid.getEditor().editItem(person);
    });
    editButton.getStyle().set("color", "#000000");
    return editButton;
});

this.grid.addComponentColumn(person -> {
    // edit: added click listener for person removal
    Button deleteButton = new Button(null, IronIcons.DELETE_FOREVER.create(), click -> {
        this.personDao.remove(person);
        // TODO: when using an in-memory dataprovider, fetch all items again from service/dao and set them with grid.setItems(this.personDao.findAll());
        // but that is not necessary when using a callback dataprovider, which I belive OP is using
        this.grid.getDataProvider().refresh();
    });
    deleteButton.getStyle().set("color", "#000000");
    return deleteButton;
}
this.addComponentAsFirst(this.grid);

编辑:一件小事,但我仍然想提一下 - 您创建了一些不必要的列,但稍后又将它们全部删除。您可以通过将 false 作为 Grid 构造函数的第二个参数传递给网格,而不是首先告诉网格不要创建这些列。

this.grid = new Grid(Person.class, false);

// instead of

this.grid = new Grid(Person.class);
this.grid.removeAllColumns();