How to add button in a Grid in Vaadin

herman shafiq picture herman shafiq · Mar 29, 2016 · Viewed 10.4k times · Source

Hi Im try to add button in a grid in vaadin but it print the reference on button object.

Grid statementEnquiriesList = new Grid();
statementEnquiriesList.addColumn("", Button.class);
        statementEnquiriesList.addColumn("DATE/TIME", String.class);
        statementEnquiriesList.addColumn("TRANSACTION ID", String.class);
        statementEnquiriesList.addColumn("FROM", String.class);

// historyList is an array object
for (int i = 0; i < historyList.size(); i++)
{
    HistoryList recordObj = historyList.get(i);
    Button addBtn = new Button();
    addBtn.setCaption("Add");
    statementEnquiriesList.addRow(addBtn , recordObj.getDate(), recordObj.getTransactionId(), recordObj.getFrom());
}

how can i print "Add" caption on this

enter image description here

Answer

Piro says Reinstate Monica picture Piro says Reinstate Monica · Jul 11, 2017

You cannot use component in grid directly in Vaadin 7. You have to use ButtonRenderer to render a button

RendererClickListener ownerClickListener = new RendererClickListener() {

    private static final long serialVersionUID = 1L;

    @Override
    public void click(RendererClickEvent event) {
        //Someone clicked button
    }
};
ButtonRenderer ownerRenderer = new ButtonRenderer(ownerClickListener, "");
grid.getColumn("ownerName").setRenderer(ownerRenderer);

But you can use components in Vaadin 8, see Grid Components in Vaadin 8.

I am using Vaadin 7 and ButtonRenderer was unsatisfactory for me because there is no way to add FontIcon to button and there is no way to insert it as HTML. Instead I used component renderer addon. Here is how I used it:

Grid grid = new Grid();
BeanItemContainer<EventChange> dataSource = //... primary data source
GeneratedPropertyContainer dataSource2 = new GeneratedPropertyContainer(dataSource);
grid.setContainerDataSource(dataSource2);
dataSource2.addGeneratedProperty("ownerWithButton", new PropertyValueGenerator<Component>() {

        private static final long serialVersionUID = 1L;

        @Override
        public Component getValue(Item item, Object itemId, Object propertyId) {
            ClickListener ownerClickListener = new ClickListener() {

                private static final long serialVersionUID = 1L;
                @Override
                public void buttonClick(ClickEvent event) {
                    // do something, user clicked button for itemId
                }
            };
            Button button = new Button(FontAwesome.USER);
            button.addClickListener(ownerClickListener);
            return button;
        }

        @Override
        public Class<Component> getType() {
            return Component.class;
        }
    });
grid.setColumns("ownerWithButton", /*and rest of your columns*/);
grid.getColumn("ownerWithButton").setRenderer( new ComponentRenderer());