如何添加组合框以过滤vaadin Grid列

时间:2016-09-30 08:54:27

标签: java combobox grid vaadin vaadin7

我必须添加一个组合框用于过滤vaadin网格列。组合框将显示网格的列,我创建了一个网格并从域类中获取数据。 代码如下

static constraints = {

        title nullable:true, blank:true

    }

我需要一个comboBox,网格中包含值代码,姓氏,名字,公司

1 个答案:

答案 0 :(得分:0)

您可以从网格中获取列,也可以将其作为ComboBox中的项目。为此,我定义了一个类GridColumn,它表示我们感兴趣的com.vaadin.ui.Grid.Column的属性(即id和标题标题):

<强> GridColumn.java

/**
 * Represents a column in a Vaadin Grid
 */
public class GridColumn {

    private String id; // propertyId in com.vaadin.ui.Grid.Column

    private String header; // headerCaption in com.vaadin.ui.Grid.Column

    // Getters and setters omitted

}

然后可以使用以下代码构建相关的UI组件(Grid和ComboBox),然后添加到布局中:

    // Adapted from your code
    List<Partner> partnerList = new ArrayList<Partner>();
    partnerList.add(new Partner("AB", "Smith", "James", "Company A"));
    partnerList.add(new Partner("DD", "Jones", "Robin", "Company B"));

    BeanItemContainer<Partner> container = new BeanItemContainer<Partner>(Partner.class, partnerList);

    Grid grid = new Grid();
    grid.setColumns("code", "surname", "name", "companyName");

    grid.getColumn("code").setHeaderCaption("Code");
    grid.getColumn("lastname").setHeaderCaption("Last Name");
    grid.getColumn("name").setHeaderCaption("First Name");
    grid.getColumn("companyName").setHeaderCaption("Company");

    grid.setContainerDataSource(container);

    // Get the list of columns and as them as ComboBox items
    List<Column> cols = grid.getColumns();
    List<GridColumn> comboItems = new ArrayList<>();
    for (Column column : cols) {
        GridColumn col = new GridColumn();
        col.setHeader(column.getHeaderCaption()); // Column Header Caption
        col.setId((String) column.getPropertyId()); // Column "id"
        comboItems.add(col);
    }

    // Construction of the ComboBox
    ComboBox combo = new ComboBox();
    // Use the List<GridColumn> as the container for the ComboBox items
    combo.setContainerDataSource(new BeanItemContainer<GridColumn>(GridColumn.class, comboItems));
    // Property of GridColumn to use as the value to display in the ComboBox
    combo.setItemCaptionPropertyId("header");

    combo.addBlurListener(e -> {
        // Upon selection of a column, update the grid to only display that column
        GridColumn selected = (GridColumn) combo.getValue();
        System.out.println("Selected value is " + selected);
        grid.setColumns(selected.getId());
        grid.getColumn(selected.getId()).setHeaderCaption(selected.getHeader());
    });

    addComponents(combo, grid);

在ComboBox上存在一个blurListener,这样当选择一个值(并且焦点离开ComboBox)时,它会更新Grid以仅显示所选列。

图1:加载时(显示所有列)

enter image description here

图2:行动中的ComboBox

enter image description here

图3:选择ComboBox中的项目会导致表格仅显示该列

enter image description here

相关问题