Need a grid layout similar to excel with check box in each row to select a

Hi All,
I’m new to vaadin, and trying to make a gridlayout page similar to excel in which I’m loading the datas from a DB, and here I want a checkbox for each row as the first entry in row and I need few columns to freezed so that only the rest of the columns will be scrollable horizontally, here my requirement is to select some rows by checking the checkbox and edit the values and save the selected rows to db. I’m able to get table structure in my test project but I’m not getting any ideas on below points

1.Not able to get the check boxes as the first coulmn in table
2. Not able handle unchecking event in check box. i.e whenever i select a row using check box, I need all the data in a List or somewhere and when its unchecked it should be removed from the same list, so that i could save the selected rows to db(Getting a concurrent modification exception)
3. I have no idea on how to freeze a column.

Below is my code, and attached is the way i want the page to look like. Please help me in this, i need a help desperately.

I’m using stored procedure to get data from db, only the second column is editable here.

package com.example.vaadintest;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.annotation.WebServlet;

import com.example.dao.States;
import com.jensjansson.pagedtable.PagedTable;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.Field;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import com.vaadin.ui.TableFieldFactory;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

@SuppressWarnings(“serial”)
@Theme(“vaadintest”)
public class VaadintestUI extends UI implements View {
VerticalLayout mainVL = new VerticalLayout();
HorizontalLayout tableHL = new HorizontalLayout();
IndexedContainer resultContainer = new IndexedContainer();
PagedTable resultsTable = new PagedTable();
IndexedContainer resultContainer1 = new IndexedContainer();
PagedTable resultsTable1 = new PagedTable();
HorizontalLayout subHLOne = new HorizontalLayout();
VerticalLayout subVLOne = new VerticalLayout();
VerticalLayout subVLTwo = new VerticalLayout();
HorizontalLayout buttonsHL = new HorizontalLayout();
HorizontalLayout searchHL = new HorizontalLayout();
Button saveButton = new Button();
HorizontalLayout tableHL1 = new HorizontalLayout();
TextField tfName = new TextField(“ID”);
TextField tfState = new TextField(“State”);
TextField tfPopulation = new TextField(“Population”);
List stateList = new ArrayList();
List stateListChanged = new ArrayList();
List stateListChangedTemp = new ArrayList();
States temp = new States();
final static String PERSISTENCE_UNIT_NAME = “com.test.jpa”;
private static final Object CHECKBOX_COLUMN = “selected”;
static EntityManagerFactory factory = Persistence
.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = VaadintestUI.class)
public static class Servlet extends VaadinServlet {
}

@Override
protected void init(VaadinRequest request) {
    mainVL.setMargin(true);
    setContent(mainVL);
    createTable();
    populateComponents();
}

@Override
public void enter(ViewChangeEvent event) {
}

private void populateComponents() {

    VerticalLayout vertical = new VerticalLayout();
    mainVL.setSpacing(true);
    mainVL.addComponent(subHLOne);
    subHLOne.addComponent(subVLOne);
    subVLOne.setSpacing(true);
    subHLOne.addComponent(vertical);
    buttonsHL.addStyleName("ButtonsHL");
    subVLOne.addComponent(buttonsHL);
    buttonsHL.addComponent(saveButton);
    saveButton.setCaption("Save");
    saveButton.addClickListener(new ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            // Logic to save the selected list of rows to db
            // Get the list of selected rows iterate and save the same to db
            // by comparing primary key
        }
    });
}

@SuppressWarnings({ "unchecked" })
public void createTable() {

    resultContainer = getResultsContainer();
    setWidth(resultContainer, resultsTable);
    resultsTable.addGeneratedColumn(CHECKBOX_COLUMN,
            new Table.ColumnGenerator() {
                @Override
                public Component generateCell(final Table source,
                        final Object itemId, Object columnId) {
                    final CheckBox checkBox = new CheckBox("",
                            isItemIdSelected(source, itemId));
                    checkBox.addValueChangeListener(new Property.ValueChangeListener() {
                        @Override
                        public void valueChange(
                                Property.ValueChangeEvent valueChangeEvent) {
                            Boolean selected = (Boolean) valueChangeEvent
                                    .getProperty().getValue();
                            if (selected) {
                                States state = new States();
                                state.setPopulation(resultContainer
                                        .getItem(itemId)
                                        .getItemProperty("Population")
                                        .getValue().toString());
                                state.setState(resultContainer
                                        .getItem(itemId)
                                        .getItemProperty("State")
                                        .getValue().toString());
                                stateListChanged.add(state);
                                source.select(itemId);
                            } else {
                                source.unselect(itemId);
                                for (States state : stateListChanged) {
                                    if (state.getState().equals(
                                            resultContainer
                                                    .getItem(itemId)
                                                    .getItemProperty(
                                                            "State")
                                                    .getValue().toString()))
                                        stateListChanged.remove(state);
                                }
                            }
                        }
                    });
                    return checkBox;
                }
            });
    EntityManager em = factory.createEntityManager();
    Query query = em.createNativeQuery("{ CALL getStatesOrderby1() }");
    List<States> stateList = query.getResultList();
    for (Object object : stateList) {
        Object[] obj = (Object[]

) object;
Object obj1 = resultContainer.addItem();
Item item = resultContainer.getItem(obj1);
item.getItemProperty(“State”).setValue(String.valueOf(obj[1]
));
item.getItemProperty(“Population”).setValue(
Integer.parseInt((obj[2]
).toString()));
}
resultsTable.setContainerDataSource(resultContainer);
resultsTable.addStyleName(“wordwrap”);
resultsTable.addStyleName(“wordwrap-headers”);
resultsTable.setVisible(true);
resultsTable.setSelectable(true);
resultsTable.setImmediate(true);
resultsTable.setPageLength(resultsTable.size());
subVLOne.addComponent(resultsTable);
resultsTable.setEditable(true);
resultsTable.setHeight(“100%”);
resultsTable.setTableFieldFactory(new TableFieldFactory() {
@SuppressWarnings(“rawtypes”)
public Field createField(Container container, Object itemId,
Object propertyId, Component uiContext) {
TextField field = new TextField((String) propertyId);
if (“State”.equals(propertyId))
field.setReadOnly(true);
else {
field.setData(itemId);
if (((Integer) itemId) == 0)
field.focus();
}
return field;
}
});
}

@SuppressWarnings("rawtypes")
protected boolean isItemIdSelected(Table select, Object itemId) {

    Object value = select.getValue();
    if (itemId == null || value == null) {
        return false;
    }
    if (select.isMultiSelect()) {
        return ((Collection) value).contains(itemId);
    }
    return itemId.equals(value);
}

@SuppressWarnings("unchecked")
public void createResultTable(List<States> stateList) {
    resultContainer1 = getResultsContainer();
    setWidth(resultContainer1, resultsTable1);
    for (Object object : stateList) {
        Object[] obj = (Object[]

) object;
Object obj1 = resultContainer1.addItem();
Item item = resultContainer1.getItem(obj1);
item.getItemProperty(“State”).setValue(String.valueOf(obj[1]
));
item.getItemProperty(“Population”).setValue(
Integer.parseInt((obj[2]
).toString()));

    }
    resultsTable1.setContainerDataSource(resultContainer1);
    resultsTable1.addStyleName("wordwrap");
    resultsTable1.addStyleName("wordwrap-headers");
    resultsTable1.setVisible(true);
    resultsTable1.setSelectable(true);
    resultsTable1.setImmediate(true);
    resultsTable1.setPageLength(resultsTable1.size());
    subVLOne.addComponent(resultsTable1);
}

public IndexedContainer getResultsContainer() {
    IndexedContainer container = new IndexedContainer();
    container.addContainerProperty("State", String.class, "");
    container.addContainerProperty("Population", Integer.class, "");
    return container;
}

public void setWidth(IndexedContainer resultContainer,
        PagedTable iasResultsTable) {
    iasResultsTable.setColumnWidth("State", 100);
    iasResultsTable.setColumnWidth("Population", 80);
}

}
17622.jpg

Hi,

Your problem description lists all the features in the new Grid component (currently in beta stage). You should check that one out, if you can use it to your advantage in this case. Grid is basicly a table with features like multiselect using checkboxes, freezing columns, lazy loading data from a backend.

//Teemu

Any idea, which is that component/when can we expect its launching; and any idea to get it done with the existing table component, at least to get the checkbox as the first coulmn in table?

Hi,

Grid is a better table component available in the new 7.4 Vaadin version. It’s currently in the beta stage, so the current version is 7.4.0.beta1. Most of the documentation is still work in progress but what features you wanted, those are easily accessible. For making the same with Table? I need to search through some documentation if something like that has been done. I’d guess it needs more than just server side code.

//Teemu

Hi Teemu,
I managed to get the structure, except freezing of first two or three column when i have large number of coulmns, if you can give any light on the same, it would be greatful. Below is my code.

package com.example.testtable;


import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.AbstractSelect;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.Field;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import com.vaadin.ui.TableFieldFactory;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.annotation.WebServlet;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@SuppressWarnings("serial")
public class CheckboxTable extends UI {

    private static final String CHECKBOX_COLUMN = "selected";
    protected Map<Object, CheckBox> itemIdToCheckbox = new Hashtable<Object, CheckBox>();
    Iterator<Object> keySetItr;
    final static String PERSISTENCE_UNIT_NAME = "com.test.jpa";
    static EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    List<State> stateListChanged = new ArrayList<State>();
    IndexedContainer container = new IndexedContainer();

    @WebServlet(value = "/*", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = false, ui = CheckboxTable.class)
    public static class Servlet extends VaadinServlet {
    }

    @Override
    protected void init(VaadinRequest request) {
        VerticalLayout mainLayout = new VerticalLayout();
        HorizontalLayout tableHL = new HorizontalLayout();
        HorizontalLayout buttonsHL = new HorizontalLayout();
        
        Table table = createTable();
        tableHL.addComponent(table);
        Button saveButton = new Button();
        
        buttonsHL.addComponent(saveButton);
        saveButton.setCaption("Save");
        
        mainLayout.addComponent(tableHL);
        mainLayout.addComponent(buttonsHL);
        setContent(mainLayout);
        saveButton.addClickListener(new ClickListener() {
            @Override
            public void buttonClick(ClickEvent event) {
                for (Object itemID : itemIdToCheckbox.keySet()) {
                    System.out.println(container.getItem(itemID).getItemProperty("State").getValue().toString()+ " "+container.getItem(itemID).getItemProperty("Population").getValue().toString());
                }
                //itemIdToCheckbox.clear();
            }
        });
    }
    @SuppressWarnings("unchecked")
    private Table createTable() {
        final Table table = new Table();
        table.addGeneratedColumn(CHECKBOX_COLUMN, new Table.ColumnGenerator() {
            @Override
            public Object generateCell(final Table source, final Object itemId,
                    Object columnId) {

                final CheckBox checkBox = new CheckBox("", isItemIdSelected(
                        source, itemId));
                checkBox.addValueChangeListener(new Property.ValueChangeListener() {
                    @Override
                    public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
                            Boolean selected = (Boolean) valueChangeEvent.getProperty().getValue();
                            if (selected) {
                                itemIdToCheckbox.put(itemId, checkBox);
                                source.select(itemId);
                            } else {
                                source.unselect(itemId);
                                keySetItr = itemIdToCheckbox.keySet().iterator();
                                while (keySetItr.hasNext()) {
                                    Object key = keySetItr.next();
                                    if (key.toString().equals(itemId.toString())) {
                                        keySetItr.remove();
                                    }
                                }
                            }
                    }
                });
                return checkBox;
            }
        });
        table.setMultiSelect(true);
        table.setSelectable(true);
        table.setEditable(true);
        //table.setPageLength();
        table.addItemClickListener(new ItemClickListener() {
            
            @Override
            public void itemClick(ItemClickEvent event) {
                
                
            }
        });
        table.setTableFieldFactory(new TableFieldFactory() {
            @SuppressWarnings("rawtypes")
            public Field createField(Container container, Object itemId,
                    Object propertyId, Component uiContext) {
                TextField field = new TextField((String) propertyId);
                if ("State".equals(propertyId))
                    field.setReadOnly(true);
                else {
                    field.setData(itemId);
                    field.focus();
                }
                return field;
            }
        });
        container.addContainerProperty("State", String.class, null);
        container.addContainerProperty("Population", Integer.class, null);
        EntityManager em = factory.createEntityManager();
        Query query = em.createNativeQuery("{ CALL getStatesOrderby1() }");
        List<State> stateList = query.getResultList();
        for (Object object : stateList) {
            Object obj = (Object) object;
            Object obj1 = container.addItem();
            Item item = container.getItem(obj1);
            item.getItemProperty("State").setValue(String.valueOf(obj[1]
));
            item.getItemProperty("Population").setValue(
                    Integer.parseInt((obj[2]
).toString()));
        }
        table.setContainerDataSource(container);
        table.setVisibleColumns(CHECKBOX_COLUMN, "State", "Population");
        return table;
    }

    @SuppressWarnings("rawtypes")
    protected boolean isItemIdSelected(AbstractSelect select, Object itemId) {
        Object value = select.getValue();
        if (itemId == null || value == null) {
            return false;
        }

        if (select.isMultiSelect()) {
            return ((Collection) value).contains(itemId);
        }

        return itemId.equals(value);
    }
}