Vaadin addComponentColumn работает только в последней строке - PullRequest
0 голосов
/ 25 октября 2019
    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 с несколькими записями. Сетка показывает все эти записи с их именем. Но он показывает только кнопки в последнем ряду. В чем проблема?

1 Ответ

5 голосов
/ 25 октября 2019

Вы используете один и тот же экземпляр Button для каждой строки. Вы должны создать новую кнопку внутри componentRenderer, чтобы у каждой строки была своя собственная кнопка.

Попробуйте это так:

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();
...