Example usage for com.vaadin.ui Grid setFrozenColumnCount

List of usage examples for com.vaadin.ui Grid setFrozenColumnCount

Introduction

In this page you can find the example usage for com.vaadin.ui Grid setFrozenColumnCount.

Prototype

public void setFrozenColumnCount(int numberOfColumns) 

Source Link

Document

Sets the number of frozen columns in this grid.

Usage

From source file:de.datenhahn.vaadin.componentrenderer.demo.ClassicGridTab.java

License:Apache License

private void init() {
    setSizeFull();/*from   w  ww .ja va2 s  .c  o  m*/
    setMargin(true);
    setSpacing(true);

    addComponent(
            new Label("Look at the sourcecode to see the difference between the typed ComponentGrid and using"
                    + " the classic grid"));

    Grid grid = new Grid();
    ComponentCellKeyExtension.extend(grid);
    focusPreserveExtension = FocusPreserveExtension.extend(grid);
    DetailsKeysExtension.extend(grid);

    addComponent(ViewComponents.createEnableDisableCheckBox(grid));

    grid.setSizeFull();

    // Initialize Containers
    BeanItemContainer<Customer> bc = new BeanItemContainer<>(Customer.class);

    GeneratedPropertyContainer gpc = new GeneratedPropertyContainer(bc);
    grid.setContainerDataSource(gpc);

    // Load the data
    bc.addAll(CustomerProvider.createDummyData());

    // Initialize DetailsGenerator (Caution: the DetailsGenerator is set to null
    // when grid#setContainerDatasource is called, so make sure you call setDetailsGenerator
    // after setContainerDatasource
    grid.setDetailsGenerator(new CustomerDetailsGenerator());

    gpc.addGeneratedProperty(Customer.FOOD, new PropertyValueGenerator<Component>() {
        @Override
        public Component getValue(Item item, Object itemId, Object propertyId) {
            return ViewComponents.createClassicFoodSelector(grid, focusPreserveExtension, (Customer) itemId);
        }

        @Override
        public Class<Component> getType() {
            return Component.class;
        }

        // You must override getSortProperties to allow sorting by the values
        // underlying of the GeneratedValue. The default is that generated
        // property columns cannot be sorted (see PropertyValueGenerator default implementation)
        // if the generated column is not shadowing a real data column DO NOT overwrite this method
        // otherwise an exception is thrown when you sort it because the bean property cannot be found
        @Override
        public SortOrder[] getSortProperties(SortOrder order) {
            return new SortOrder[] { order };
        }
    });

    // Don't forget to set the ComponentRenderer AFTER adding the column
    grid.getColumn(Customer.FOOD).setRenderer(new ComponentRenderer());

    gpc.addGeneratedProperty(GENERATED_FOOD_ICON, new PropertyValueGenerator<Component>() {
        @Override
        public Component getValue(Item item, Object itemId, Object propertyId) {
            return ViewComponents.createFoodIcon((Customer) itemId);
        }

        @Override
        public Class<Component> getType() {
            return Component.class;
        }

        // You must override getSortProperties to allow sorting by the values
        // underlying of the GeneratedValue. The default is that generated
        // property columns cannot be sorted (see PropertyValueGenerator default implementation)
        // if the generated column is not shadowing a real data column DO NOT overwrite this method
        // otherwise an exception is thrown when you sort it because the bean property cannot be found
        @Override
        public SortOrder[] getSortProperties(SortOrder order) {
            return new SortOrder[] { order };
        }
    });

    // Don't forget to set the ComponentRenderer AFTER adding the column
    grid.getColumn(GENERATED_FOOD_ICON).setRenderer(new ComponentRenderer());

    gpc.addGeneratedProperty(GENERATED_RATING, new PropertyValueGenerator<Component>() {
        @Override
        public Component getValue(Item item, Object itemId, Object propertyId) {
            return ViewComponents.createRating((Customer) itemId);
        }

        @Override
        public Class<Component> getType() {
            return Component.class;
        }

    });

    // Don't forget to set the ComponentRenderer AFTER adding the column
    grid.getColumn(GENERATED_RATING).setRenderer(new ComponentRenderer());

    gpc.addGeneratedProperty(GENERATED_DELETE, new PropertyValueGenerator<Component>() {
        @Override
        public Component getValue(Item item, Object itemId, Object propertyId) {
            return ViewComponents.createClassicDeleteButton(grid, focusPreserveExtension, bc,
                    (Customer) itemId);
        }

        @Override
        public Class<Component> getType() {
            return Component.class;
        }

    });

    // Don't forget to set the ComponentRenderer AFTER adding the column
    grid.getColumn(GENERATED_DELETE).setRenderer(new ComponentRenderer());

    gpc.addGeneratedProperty(GENERATED_DETAILS_ICONS, new PropertyValueGenerator<Component>() {
        @Override
        public Component getValue(Item item, Object itemId, Object propertyId) {
            return ViewComponents.createDetailsIcons(grid, (Customer) itemId);
        }

        @Override
        public Class<Component> getType() {
            return Component.class;
        }

    });

    // Don't forget to set the ComponentRenderer AFTER adding the column
    grid.getColumn(GENERATED_DETAILS_ICONS).setRenderer(new ComponentRenderer());

    // always display the details column
    grid.setFrozenColumnCount(1);

    grid.setColumns(GENERATED_DETAILS_ICONS, Customer.ID, Customer.FIRST_NAME, Customer.LAST_NAME,
            Customer.FOOD, GENERATED_FOOD_ICON, GENERATED_RATING, GENERATED_DELETE);

    addComponent(grid);
    setExpandRatio(grid, 1.0f);
}

From source file:de.datenhahn.vaadin.componentrenderer.demo.ClassicGridWithDecoratorTab.java

License:Apache License

private void init() {
    setSizeFull();/*from ww  w .  j a  va  2  s.  com*/
    setMargin(true);
    setSpacing(true);

    addComponent(new Label("This grid is editable using the grid's editor"));

    Grid grid = new Grid();
    grid.setContainerDataSource(new BeanItemContainer<Customer>(Customer.class));
    ComponentGridDecorator<Customer> componentGridDecorator = new ComponentGridDecorator<>(grid,
            Customer.class);
    componentGridDecorator.addAll(CustomerProvider.createDummyData());
    addComponent(ViewComponents.createEnableDisableCheckBox(grid));

    grid.setSizeFull();
    grid.setEditorEnabled(true);
    grid.setEditorBuffered(false);

    // Initialize DetailsGenerator (Caution: the DetailsGenerator is set to null
    // when grid#setContainerDatasource is called, so make sure you call setDetailsGenerator
    // after setContainerDatasource
    grid.setDetailsGenerator(new CustomerDetailsGenerator());

    componentGridDecorator.addComponentColumn(Customer.PREMIUM,
            cust -> ViewComponents.createPremiumCheckbox(componentGridDecorator, cust));
    componentGridDecorator.addComponentColumn(Customer.FOOD,
            cust -> ViewComponents.createFoodSelector(componentGridDecorator, cust));
    componentGridDecorator.addComponentColumn(GENERATED_FOOD_ICON, cust -> ViewComponents.createFoodIcon(cust));
    componentGridDecorator.addComponentColumn(GENERATED_RATING, cust -> ViewComponents.createRating(cust));
    componentGridDecorator.addComponentColumn(GENERATED_DELETE,
            cust -> ViewComponents.createDeleteButton(componentGridDecorator, cust)).setEditable(false);
    componentGridDecorator
            .addComponentColumn(GENERATED_DETAILS_ICONS, cust -> ViewComponents.createDetailsIcons(grid, cust))
            .setEditable(false);

    // always display the details column
    grid.setFrozenColumnCount(1);

    grid.setColumns(GENERATED_DETAILS_ICONS, Customer.ID, Customer.PREMIUM, Customer.FIRST_NAME,
            Customer.LAST_NAME, Customer.FOOD, GENERATED_FOOD_ICON, GENERATED_RATING, GENERATED_DELETE);
    //grid.setColumns(Customer.PREMIUM, Customer.FIRST_NAME, Customer.LAST_NAME, GENERATED_RATING);
    componentGridDecorator.generateHeaders(new ResourceBundleTextHeaderGenerator(ViewComponents.getLabels()));

    addComponent(grid);
    setExpandRatio(grid, 1.0f);
}

From source file:de.datenhahn.vaadin.componentrenderer.demo.ClassicGridWithStaticContainerTab.java

License:Apache License

private void init() {
    setSizeFull();/* w  ww  .  j a v a2  s  . c  om*/
    setMargin(true);
    setSpacing(true);

    addComponent(
            new Label("Look at the sourcecode to see the difference between the typed ComponentGrid and using"
                    + " the classic grid"));

    Grid grid = new Grid();
    ComponentCellKeyExtension.extend(grid);
    focusPreserveExtension = FocusPreserveExtension.extend(grid);
    DetailsKeysExtension.extend(grid);

    addComponent(ViewComponents.createEnableDisableCheckBox(grid));
    grid.setSelectionMode(Grid.SelectionMode.SINGLE);

    ((Grid.SingleSelectionModel) grid.getSelectionModel()).setDeselectAllowed(false);
    grid.setImmediate(true);

    grid.setSizeFull();

    // Initialize Containers
    BeanItemContainer<StaticCustomer> bc = new BeanItemContainer<>(StaticCustomer.class);

    grid.setContainerDataSource(bc);

    // Load the data
    bc.addAll(StaticCustomerProvider.createDummyData());

    // Initialize DetailsGenerator (Caution: the DetailsGenerator is set to null
    // when grid#setContainerDatasource is called, so make sure you call setDetailsGenerator
    // after setContainerDatasource
    grid.setDetailsGenerator(new StaticCustomerDetailsGenerator());

    // always display the details column
    grid.setFrozenColumnCount(1);

    grid.getColumn(Customer.FOOD).setRenderer(new ComponentRenderer());

    grid.setColumns(StaticCustomer.ID, StaticCustomer.FIRST_NAME, StaticCustomer.LAST_NAME,
            StaticCustomer.FOOD);

    addComponent(grid);
    setExpandRatio(grid, 1.0f);
}

From source file:de.kaiserpfalzEdv.vaadin.about.AboutViewImpl.java

License:Apache License

private void initializeModuleVersions() {
    versionLayout = createVerticalLayout("about.modules.caption", "about.modules.description",
            FontAwesome.LIST);//w  ww .java2 s .c o m

    BeanItemContainer<ModuleVersion> data = new BeanItemContainer<>(ModuleVersion.class);
    data.addAll(versions);

    Grid display = new Grid(data);
    display.setSizeFull();
    display.setFrozenColumnCount(1);
    display.setColumns("caption", "description", "version");

    formatColumn(display, "caption", "about.modules", 25);
    formatColumn(display, "description", "about.modules", 50);
    formatColumn(display, "version", "about.modules", 25);
    versionLayout.addComponent(display);
}

From source file:de.kaiserpfalzEdv.vaadin.about.AboutViewImpl.java

License:Apache License

private void initializeDatabaseChangeLog() {
    changelogLayout = createVerticalLayout("about.database.caption", "about.database.description",
            FontAwesome.TABLE);//from w w  w . j  av  a 2 s  . c  om

    BeanItemContainer<DatabaseChangeLog> data = new BeanItemContainer<>(DatabaseChangeLog.class);
    data.addAll(changeLog);

    Grid display = new Grid(data);
    display.setSizeFull();
    display.setFrozenColumnCount(1);
    display.setColumns("id", "fileName", "dateExecuted", "comments", "liquibase");

    formatColumn(display, "id", "about.database", 10);
    formatColumn(display, "fileName", "about.database", 20);
    formatColumn(display, "dateExecuted", "about.database", 20);
    formatColumn(display, "comments", "about.database", 40);
    formatColumn(display, "liquibase", "about.database", 10);
    changelogLayout.addComponent(display);
}

From source file:org.jumpmind.vaadin.ui.common.CommonUiUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
public static Grid putResultsInGrid(final ResultSet rs, List<Integer> pkcolumns, int maxResultSize,
        final boolean showRowNumbers, String... excludeValues) throws SQLException {

    final Grid grid = new Grid();
    grid.setImmediate(true);/*from  w ww.  j  av a2 s. c o  m*/
    grid.setSelectionMode(SelectionMode.MULTI);
    grid.setColumnReorderingAllowed(true);
    grid.setData(new HashMap<Object, List<Object>>());

    final ResultSetMetaData meta = rs.getMetaData();
    int columnCount = meta.getColumnCount();
    grid.addColumn("#", Integer.class).setHeaderCaption("#").setHidable(true);
    Set<String> columnNames = new HashSet<String>();
    Set<Integer> skipColumnIndexes = new HashSet<Integer>();
    int[] types = new int[columnCount];
    for (int i = 1; i <= columnCount; i++) {
        String realColumnName = meta.getColumnName(i);
        String columnName = realColumnName;
        if (!Arrays.asList(excludeValues).contains(columnName)) {

            int index = 1;
            while (columnNames.contains(columnName)) {
                columnName = realColumnName + "_" + index++;
            }
            columnNames.add(columnName);

            Class<?> typeClass = Object.class;
            int type = meta.getColumnType(i);
            types[i - 1] = type;
            switch (type) {
            case Types.FLOAT:
            case Types.DOUBLE:
            case Types.NUMERIC:
            case Types.REAL:
            case Types.DECIMAL:
                typeClass = BigDecimal.class;
                break;
            case Types.TINYINT:
            case Types.SMALLINT:
            case Types.BIGINT:
            case Types.INTEGER:
                typeClass = Long.class;
                break;
            case Types.VARCHAR:
            case Types.CHAR:
            case Types.NVARCHAR:
            case Types.NCHAR:
            case Types.CLOB:
                typeClass = String.class;
            default:
                break;
            }
            Column column = grid.addColumn(columnName, typeClass).setHeaderCaption(columnName).setHidable(true);
            if (typeClass.equals(Long.class)) {
                column.setConverter(new StringToLongConverter() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public String convertToPresentation(Long value, Class<? extends String> targetType,
                            Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException {
                        if (value == null) {
                            return NULL_TEXT;
                        } else {
                            return value.toString();
                        }
                    }
                });
            } else if (typeClass.equals(BigDecimal.class)) {
                column.setConverter(new StringToBigDecimalConverter() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public String convertToPresentation(BigDecimal value, Class<? extends String> targetType,
                            Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException {
                        if (value == null) {
                            return NULL_TEXT;
                        } else {
                            return value.toString();
                        }
                    }
                });
            } else {
                column.setConverter(new Converter<String, Object>() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public Object convertToModel(String value, Class<? extends Object> targetType,
                            Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException {
                        return null;
                    }

                    @Override
                    public String convertToPresentation(Object value, Class<? extends String> targetType,
                            Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException {
                        if (value == null) {
                            return NULL_TEXT;
                        } else {
                            return value.toString();
                        }
                    }

                    @Override
                    public Class<Object> getModelType() {
                        return Object.class;
                    }

                    @Override
                    public Class<String> getPresentationType() {
                        return String.class;
                    }

                });
            }
        } else {
            skipColumnIndexes.add(i - 1);
        }

    }
    int rowNumber = 1;
    while (rs.next() && rowNumber <= maxResultSize) {
        Object[] row = new Object[columnNames.size() + 1];
        row[0] = new Integer(rowNumber);
        int rowIndex = 1;
        for (int i = 0; i < columnCount; i++) {
            if (!skipColumnIndexes.contains(i)) {
                Object o = getObject(rs, i + 1);
                int type = types[i];
                switch (type) {
                case Types.FLOAT:
                case Types.DOUBLE:
                case Types.REAL:
                case Types.NUMERIC:
                case Types.DECIMAL:
                    if (o != null && !(o instanceof BigDecimal)) {
                        o = new BigDecimal(castToNumber(o.toString()));
                    }
                    break;
                case Types.TINYINT:
                case Types.SMALLINT:
                case Types.BIGINT:
                case Types.INTEGER:
                    if (o != null && !(o instanceof Long)) {
                        o = new Long(castToNumber(o.toString()));
                    }
                    break;
                default:
                    break;
                }
                List<Object> primaryKeys = new ArrayList<Object>();
                for (Integer pkcolumn : pkcolumns) {
                    primaryKeys.add(getObject(rs, pkcolumn + 1));
                }
                ((HashMap<Object, List<Object>>) grid.getData()).put(o, primaryKeys);
                row[rowIndex] = o;
                rowIndex++;
            }
        }
        grid.addRow(row);
        rowNumber++;
    }

    if (rowNumber < 100) {
        grid.getColumn("#").setWidth(75);
    } else if (rowNumber < 1000) {
        grid.getColumn("#").setWidth(95);
    } else {
        grid.getColumn("#").setWidth(115);
    }

    if (!showRowNumbers) {
        grid.getColumn("#").setHidden(true);
    } else {
        grid.setFrozenColumnCount(1);
    }

    return grid;
}

From source file:org.vaadin.allaboutgrid.AllAboutGridUI.java

License:Apache License

private void initializeGrid(final Grid grid) {

    /*/*from   w w w .j a v a2  s  .c  o  m*/
     * Let's just add some data there to get something showing
     */

    // grid.addColumn("Col 1");
    // grid.addColumn("Col 2");
    //
    // grid.addRow("Some", "data");
    // grid.addRow("Another", "row");

    /*
     * Let's use a full-featured container instead
     */

    BeanItemContainer<Order> orderContainer = createOrderContainer();
    grid.setContainerDataSource(orderContainer);

    /*
     * Changing the column order and adjusting column headers
     */

    grid.setColumnOrder("id", "customer", "product", "orderAmount", "reservedAmount", "completePercentage",
            "priority", "customized", "orderTime");

    grid.getColumn("orderAmount").setHeaderCaption("Ordered");
    grid.getColumn("reservedAmount").setHeaderCaption("Reserved");
    grid.getColumn("completePercentage").setHeaderCaption("Complete");
    grid.getColumn("customized").setHeaderCaption("Custom");

    /*
     * Removing unwanted columns
     */

    // grid.removeColumn("customer");
    // grid.removeColumn("customized");
    // grid.removeColumn("priority");
    // grid.removeColumn("orderTime");

    /*
     * Adjusting column sizes
     */

    grid.getColumn("id").setMaximumWidth(70);

    grid.getColumn("customer").setMinimumWidth(200);
    grid.getColumn("product").setMinimumWidth(200);

    /*
     * Keep some columns in view all the time
     */

    grid.getColumn("product").setLastFrozenColumn();

    /*
     * Changing the locale affects how data is presented
     */

    grid.setLocale(Locale.GERMANY);

    /*
     * Various ways of tweaking how data is shown
     */

    grid.getColumn("id").setRenderer(new NumberRenderer(idFormat));

    grid.getColumn("completePercentage")
            .setRenderer(new NumberRenderer(NumberFormat.getPercentInstance(grid.getLocale())));

    grid.getColumn("completePercentage").setRenderer(new ProgressBarRenderer());

    grid.getColumn("customized").setConverter(new BooleanToFontIconConverter());

    grid.getColumn("customized").setRenderer(new HtmlRenderer());

    grid.setCellStyleGenerator(new CellStyleGenerator() {
        @Override
        public String getStyle(CellReference cellReference) {
            if ("priority".equals(cellReference.getPropertyId())) {
                Priority priority = (Priority) cellReference.getValue();
                return "priority-" + priority.name().toLowerCase();
            } else {
                return null;
            }
        }
    });

    /*
     * Additional header spanned cells
     */

    HeaderRow extraHeader = grid.prependHeaderRow();

    extraHeader.join("orderAmount", "reservedAmount").setText("Quantity");

    extraHeader.join("priority", "customized").setText("Status");

    /*
     * Footer with various types of content
     */

    FooterRow extraFooter = grid.appendFooterRow();

    int totalOrdered = OrderUtil.getTotalOrderAmount(orderContainer);
    extraFooter.getCell("orderAmount").setText(Integer.toString(totalOrdered));

    int totalReserved = OrderUtil.getTotalReservedAmounT(orderContainer);
    extraFooter.getCell("reservedAmount").setHtml("<b>" + totalReserved + "</b>");

    extraFooter.getCell("completePercentage")
            .setComponent(new ProgressBar(totalReserved / (float) totalOrdered));

    /*
     * Enable editing
     */

    grid.setEditorEnabled(true);
    grid.setFrozenColumnCount(0);

    grid.getColumn("id").setEditable(false);
    grid.getColumn("completePercentage").setEditable(false);

    grid.getColumn("customized").getEditorField().setCaption("");

    grid.getColumn("orderTime").setEditorField(createOrderTimeField());

    Field<?> customerField = grid.getColumn("customer").getEditorField();
    customerField.setRequired(true);
    customerField.setRequiredError("Value is required");

    /*
     * Get an event when the users saves in the editor
     */

    grid.getEditorFieldGroup().addCommitHandler(new CommitHandler() {
        @Override
        public void preCommit(CommitEvent commitEvent) throws CommitException {
            // Do nothing
        }

        @Override
        public void postCommit(CommitEvent commitEvent) throws CommitException {
            Notification.show("Changes saved");
        }
    });

    /*
     * New feature going into Vaadin 7.5: Column reordering
     */

    grid.setColumnReorderingAllowed(true);

    /*
     * New feature going into Vaadin 7.5: Row details
     */

    grid.setDetailsGenerator(new DetailsGenerator() {
        @Override
        public Component getDetails(RowReference rowReference) {
            Order order = (Order) rowReference.getItemId();
            String detailsMessage = "This is a label with information about the order of " + order.getProduct()
                    + " by " + order.getCustomer() + ".";

            Button deleteButton = new Button("Delete order", new Button.ClickListener() {
                @Override
                public void buttonClick(ClickEvent event) {
                    Notification.show("Button clicked");
                }
            });

            VerticalLayout layout = new VerticalLayout(new Label(detailsMessage), deleteButton);
            layout.setMargin(true);
            layout.setSpacing(true);

            return layout;
        }
    });

    grid.addItemClickListener(new ItemClickListener() {
        @Override
        public void itemClick(ItemClickEvent event) {
            if (event.isDoubleClick()) {
                Object itemId = event.getItemId();
                grid.setDetailsVisible(itemId, !grid.isDetailsVisible(itemId));
            }
        }
    });

    grid.setEditorEnabled(false);

    /*
     * That's all. Thank you for watching!
     */
}