private Grid<HeaderGridRow> formatHeaders(String title, Map<String, List<String>> headers) { Grid<HeaderGridRow> grid = new Grid<>(HeaderGridRow.class); grid.removeAllColumns(); Column<HeaderGridRow, String> headerColumn = grid.addColumn(HeaderGridRow::getHeader) .setCaption("Header") .setExpandRatio(1); Column<HeaderGridRow, String> valuesColumn = grid.addColumn(HeaderGridRow::getValues) .setCaption("Values") .setDescriptionGenerator(HeaderGridRow::getValues) .setExpandRatio(1); grid.setItems(headers.entrySet().stream().map(HeaderGridRow::new)); grid.sort(headerColumn); HeaderRow titleRow = grid.prependHeaderRow(); titleRow.join(headerColumn, valuesColumn).setHtml(title); return grid; }
/** * Setup {@link Renderer}s and {@link Converter}s for given <code>property</code> column, using * {@link PropertyColumn} definition and falling back to defaults. * @param property Property to which the column is bound * @param column Column to setup */ protected void setupRendererAndConverter(P property, Column column) { PropertyColumn<T, P> propertyColumn = getPropertyColumn(property); if (propertyColumn != null) { // Converter if (propertyColumn.getConverter() != null) { column.setConverter(propertyColumn.getConverter()); } else { // ue default, if available getDefaultPropertyConverter(property).ifPresent((c) -> column.setConverter(c)); } // Renderer if (propertyColumn.getRenderer() != null) { column.setRenderer(propertyColumn.getRenderer()); } else { // use default getDefaultPropertyRenderer(property).ifPresent(r -> column.setRenderer(r)); } } }
private void initApplicationsGrid() { grid = new Grid<>(); // Columns grid.removeAllColumns(); Column<Application, String> appColumn = grid.addColumn(Application::getName).setCaption("Application").setExpandRatio(0); Column<Application, String> envColumn = grid.addColumn(Application::getEnvironment).setCaption("Environment").setExpandRatio(0); Column<Application, String> urlColumn = grid.addColumn(Application::getUrl).setCaption("URL").setExpandRatio(1); // Items grid.setItems(applications); // Header filter row initFilterRow(appColumn, envColumn, urlColumn); // Style grid.setStyleGenerator(app -> app.isUp() ? null : "app-down"); grid.addItemClickListener(applicationOnClick()); grid.setSizeFull(); grid.setHeightByRows(applications.size()); grid.sort(appColumn); grid.setRowHeight(40); }
@SuppressWarnings({ "unchecked", "rawtypes" }) private void setEditorBinding(P property, Column column, HasValue editor, boolean readOnly, PropertyColumn<?, ?> pc) { BindingBuilder builder = getGrid().getEditor().getBinder().forField(editor); if (pc.isRequired()) { final Localizable requiredMessage = (pc.getRequiredMessage() != null) ? pc.getRequiredMessage() : RequiredInputValidator.DEFAULT_REQUIRED_ERROR; builder.asRequired(context -> { return LocalizationContext.translate(requiredMessage, true); }); } // default validators getDefaultPropertyValidators(property).forEach(v -> builder.withValidator(new ValidatorWrapper<>(v))); // validators pc.getValidators().forEach(v -> builder.withValidator(v)); // bind column.setEditorBinding(builder.bind(getColumnId(property))); // set editable if not read-only column.setEditable(!readOnly); }
protected Renderer<?> getRenderer(final String propId) { // Grid.Column (as of 8.0.3) does not expose its renderer, we have to get it from extensions final Column<T, ?> column = getColumn(propId); if (column != null) { for (Extension each : column.getExtensions()) { if (each instanceof Renderer<?>) { return (Renderer<?>) each; } } } return null; }
private Grid<MetricsGridRow> getAllMetricsGrid(Map<String, Number> metrics) { allMetricsRows = metrics.entrySet().stream() .map(MetricsGridRow::new) .collect(Collectors.toList()); Grid<MetricsGridRow> grid = new Grid<>(MetricsGridRow.class); grid.removeAllColumns(); Column<MetricsGridRow, String> nameColumn = grid.addColumn(MetricsGridRow::getName) .setCaption("Name") .setExpandRatio(1); grid.addColumn(MetricsGridRow::getValue).setCaption("Value"); grid.setItems(allMetricsRows); grid.sort(nameColumn); grid.setSizeFull(); grid.setRowHeight(40); TextField filterInput = new TextField(); filterInput.setPlaceholder("filter by metric..."); filterInput.addValueChangeListener(e -> updateMetrics(e.getValue())); filterInput.setValueChangeMode(ValueChangeMode.LAZY); filterInput.setSizeFull(); // Header row HeaderRow filterRow = grid.addHeaderRowAt(grid.getHeaderRowCount()); filterRow.getCell(nameColumn).setComponent(filterInput); return grid; }
private void initFilterRow(Column<Application, String> appColumn, Column<Application, String> envColumn, Column<Application, String> urlColumn) { TextField filterApp = new TextField(); TextField filterEnv = new TextField(); TextField filterUrl = new TextField(); filterApp.setPlaceholder("filter by application..."); filterApp.addValueChangeListener(e -> updateApplications(e.getValue(), filterEnv.getValue(), filterUrl.getValue())); filterApp.setValueChangeMode(ValueChangeMode.LAZY); filterApp.focus(); filterApp.setSizeFull(); filterEnv.setPlaceholder("filter by environment..."); filterEnv.addValueChangeListener(e -> updateApplications(filterApp.getValue(), e.getValue(), filterUrl.getValue())); filterEnv.setValueChangeMode(ValueChangeMode.LAZY); filterEnv.setSizeFull(); filterUrl.setPlaceholder("filter by URL..."); filterUrl.addValueChangeListener(e -> updateApplications(filterApp.getValue(), filterEnv.getValue(), e.getValue())); filterUrl.setValueChangeMode(ValueChangeMode.LAZY); filterUrl.setSizeFull(); // Header row HeaderRow filterRow = grid.addHeaderRowAt(grid.getHeaderRowCount()); filterRow.getCell(appColumn).setComponent(filterApp); filterRow.getCell(envColumn).setComponent(filterEnv); filterRow.getCell(urlColumn).setComponent(filterUrl); }
@Override public List<P> getPropertyColumns() { List<Column<T, ?>> columns = getGrid().getColumns(); if (columns != null && !columns.isEmpty()) { List<P> properties = new ArrayList<>(columns.size()); for (Column<T, ?> column : columns) { properties.add(getColumnProperty(column.getId())); } return properties; } return Collections.emptyList(); }
@Override public void setPropertyColumnVisible(P property, boolean visible) { ObjectUtils.argumentNotNull(property, "Property must be not null"); String id = getColumnId(property); if (id != null) { Column<T, ?> column = getGrid().getColumn(id); if (column != null) { column.setHidden(!visible); } } }
private void hackDateColumnWidth(Grid grid) { List<Column> columns = grid.getColumns(); if (columns.isEmpty()) { return; } Column lastCol = columns.get(columns.size() - 1); if (!"orderTime".equals(lastCol.getPropertyId())) { return; } lastCol.setWidth(174); }
/** * Init selection mode */ private void initSelectionMode() { final CheckBox checkBox = new CheckBox("Multi Select"); addComponent(checkBox); checkBox.setImmediate(true); checkBox.setValue(false); checkBox.addValueChangeListener(new ValueChangeListener() { /** * */ private static final long serialVersionUID = -1261311232228188664L; @Override public void valueChange(ValueChangeEvent event) { if (checkBox.getValue()) { grid.setSelectionMode(SelectionMode.MULTI); grid.recalculateColumnWidths(); // Seems to be some bug in Vaadin Grid when expand ration is // not given the column shrinks and this is visible when // selection mode is single for (Column column : grid.getColumns()) { column.setExpandRatio(1); } } else { grid.setSelectionMode(SelectionMode.SINGLE); } } }); }
/** * Initializes basic properties of the grid */ private void initGridProperties() { grid.setHeightMode(HeightMode.ROW); grid.setWidth(100, Unit.PERCENTAGE); grid.setColumnOrder(new Object[] { "customerName", "city", "pincode", "gender" }); // Hiding is not supported by Grid, in order to remove/hide a column use // this API grid.removeColumn("customerID"); Column dob = grid.getColumn("dob"); dob.setRenderer(new DateRenderer(DateFormat .getDateInstance(DateFormat.MEDIUM))); }
private void initGridColumns() { Column customerName = grid.getColumn("customerName"); Column city = grid.getColumn("city"); Column pincode = grid.getColumn("pincode"); Column gender = grid.getColumn("gender"); Column dob = grid.getColumn("dob"); customerName.setHeaderCaption("Customer Name"); city.setHeaderCaption("City"); pincode.setHeaderCaption("Pin Code"); gender.setHeaderCaption("Gender"); dob.setHeaderCaption("Date of Birth"); // Set Column order of Grid grid.setColumnOrder("customerName", "dob", "city", "gender", "pincode"); }
/** * Sets the default properties of grid */ protected void setDefaultGridProperties() { grid.setSelectionMode(SelectionMode.SINGLE); grid.removeColumn("id"); grid.removeColumn("sales2012.totalSales"); grid.removeColumn("sales2013.totalSales"); grid.removeColumn("sales2014.totalSales"); grid.setImmediate(true); grid.setHeightMode(HeightMode.CSS); for (Column column : grid.getColumns()) { column.setExpandRatio(1); } }
private <T extends Serializable> void createNestedProperties(final Grid<T> grid, final String[] nestedProperties) { if (nestedProperties != null) { for (final String property : nestedProperties) { final Column<T, ?> addColumn = grid.addColumn(new BeanNestedPropertyValueProvider<T>(property)); addColumn.setId(property); } } }
@SuppressWarnings("unchecked") @Override public Object getCellValue(Object item, Object column) { if(column instanceof Column) { grid.getColumns().stream().map(Column::getId).collect(Collectors.toList()); return ((Column<Object, ?>) column).getValueProvider().apply(item); } return null; }
private Grid<Step> createGridForGantt() { dataProvider = new ListDataProvider<>(new ArrayList<>(gantt.getSteps())); Grid<Step> grid = new Grid<>(dataProvider); grid.setWidth(400, Unit.PIXELS); grid.setHeight(100, Unit.PERCENTAGE); Column<Step, ?> c = grid.addColumn(Step::getCaption); c.setSortable(false); c.setResizable(false); gantt.setVerticalScrollDelegateTarget(grid); return grid; }
private void configureSaveColumnVisible(final Grid grid, final String uniqueId) { final String keyStub = uniqueId + "-visible"; for (GridHeadingToPropertyId id : getColumns()) { final String setVisible = UserSettingsStorageFactory.getUserSettingsStorage() .get(keyStub + "-" + id.getPropertyId()); if (setVisible != null && !setVisible.isEmpty()) { grid.getColumn(id.getPropertyId()).setHidden(!Boolean.parseBoolean(setVisible)); } } grid.addColumnVisibilityChangeListener(new ColumnVisibilityChangeListener() { private static final long serialVersionUID = -9082974567948595049L; @Override public void columnVisibilityChanged(ColumnVisibilityChangeEvent event) { final Column column = event.getColumn(); final boolean isVisible = !column.isHidden(); UserSettingsStorageFactory.getUserSettingsStorage().store(keyStub + "-" + column.getPropertyId(), "" + isVisible); } }); }
@SuppressWarnings("unchecked") private void addActionColumn() { ((GeneratedPropertyListContainer<E>) grid.getContainerDataSource()) .addGeneratedProperty(ACTION_MENU_PROPERTY_ID, getActionMenuColumnGenerator()); final Column actionMenuColumn = grid.addColumn(ACTION_MENU_PROPERTY_ID); grid.setFrozenColumnCount(1); actionMenuColumn.setHeaderCaption(""); actionMenuColumn.setRenderer(new ComponentRenderer()); actionMenuColumn.setWidth(40); actionMenuColumn.setResizable(false); grid.setCellStyleGenerator(new CellStyleGenerator() { /** * */ private static final long serialVersionUID = 1L; @Override public String getStyle(CellReference event) { String style = ""; if (event.getPropertyId().equals(ACTION_MENU_PROPERTY_ID)) { style = "grid-actionmenu"; } return style; } }); }
private boolean isColumnResizable(final Column column) { if (!column.isResizable()) { return false; } boolean resizable = true; final WidthType widthType = columnWidthTypes.get(column.getPropertyId()); if (widthType != null) { switch (widthType) { case FREE: resizable = true; break; case INITIAL: // If there is a saved width for the column then INITIAL no // longer applies final String setting = uniqueId + "-width-" + column.getPropertyId(); final Double savedWidth = getSavedWidth(setting); resizable = (savedWidth > 0); break; case FIXED: resizable = false; break; } } return resizable; }
private void configureSaveColumnVisible(final Grid grid) { final String keyStub = uniqueId + "-visible"; for (GridHeadingV2ToPropertyId id : getColumns()) { final String setVisible = UserSettingsStorageFactory.getUserSettingsStorage() .get(keyStub + "-" + id.getPropertyId()); if (setVisible != null && !setVisible.isEmpty()) { grid.getColumn(id.getPropertyId()).setHidden(!Boolean.parseBoolean(setVisible)); } } grid.addColumnVisibilityChangeListener(new ColumnVisibilityChangeListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void columnVisibilityChanged(ColumnVisibilityChangeEvent event) { final Column column = event.getColumn(); final boolean isVisible = !column.isHidden(); UserSettingsStorageFactory.getUserSettingsStorage().store(keyStub + "-" + column.getPropertyId(), "" + isVisible); } }); }
public void setPropertyColumns(Iterable<P> columns) { ObjectUtils.argumentNotNull(columns, "Property columns must be not null"); final Object[] columnsArray = ConversionUtils.iterableAsList(columns).toArray(); switch (getRenderingMode()) { case GRID: { final Grid grid = getGrid(); // set columns grid.setColumns(columnsArray); // setup columns for (P column : columns) { Column c = grid.getColumn(column); // setup column setupGridPropertyColumn(column, c); // setup renderer and converter setupRendererAndConverter(column, c); } } break; case TABLE: { final Table table = getTable(); try { duringSetup = true; // Setup columns and check Component generated columns for (P property : columns) { // column settings setupTablePropertyColumn(property, table); // generated columns Class<?> type = getPropertyColumnType(property); if (type != null && Component.class.isAssignableFrom(type)) { if (table.getColumnGenerator(property) == null) { table.addGeneratedColumn(property, new VirtualPropertyGenerator()); } } } } finally { duringSetup = false; } // set columns table.setVisibleColumns(columnsArray); } break; default: break; } }
/** * Setup column configuration for given <code>property</code> using its {@link PropertyColumn} definition. * @param property Property to which the column is bound * @param column Column to setup */ protected void setupGridPropertyColumn(P property, Column column) { PropertyColumn<T, P> propertyColumn = getPropertyColumn(property); if (propertyColumn != null) { // header if (propertyColumn.getCaption() != null) { String header = LocalizationContext.translate(propertyColumn.getCaption(), true); if (header != null) { column.setHeaderCaption(header); } } // sortable column.setSortable(requireDataSource().getConfiguration().isPropertySortable(property)); // width if (propertyColumn.getWidth() > -1) { column.setWidth(propertyColumn.getWidth()); } if (propertyColumn.getMinWidth() > -1) { column.setMinimumWidth(propertyColumn.getMinWidth()); } if (propertyColumn.getMaxWidth() > -1) { column.setMaximumWidth(propertyColumn.getMinWidth()); } // expand if (propertyColumn.getGridExpandRatio() > -1) { column.setExpandRatio(propertyColumn.getGridExpandRatio()); } // editing if (requireDataSource().getConfiguration().isPropertyReadOnly(property)) { column.setEditable(false); } else { column.setEditable(propertyColumn.isEditable()); if (propertyColumn.isEditable()) { propertyColumn.getEditor().ifPresent(e -> column.setEditorField(e)); } } // hiding if (columnHidingAllowed && propertyColumn.isHidable()) { column.setHidable(true); if (propertyColumn.isHidden()) { column.setHidden(true); } if (propertyColumn.getHidingToggleCaption() != null) { column.setHidingToggleCaption( LocalizationContext.translate(propertyColumn.getHidingToggleCaption())); } } else { column.setHidable(false); } } }
protected Column<T, ?> getColumn(final String propId) { return columns.get(propId); }
private void initGrid() { this.grid = new Grid<>(PropertyItem.class); this.grid.removeAllColumns(); Column<PropertyItem, String> propertyColumn = this.grid.addColumn(PropertyItem::getKey) .setCaption("Property") .setExpandRatio(1); Column<PropertyItem, String> valueColumn = this.grid.addColumn(PropertyItem::getValue) .setCaption("Value") .setExpandRatio(1); Column<PropertyItem, String> originColumn = this.grid.addColumn(PropertyItem::getOrigin).setCaption("Origin"); this.grid.sort(propertyColumn); this.grid.setSizeFull(); this.grid.setRowHeight(40); // distinct origin List<String> origins = this.currentEnv.getProperties().stream() .map(PropertyItem::getOrigin) .distinct() .sorted(String::compareTo) .collect(Collectors.toList()); // Filters TextField filterProperty = new TextField(); TextField filterValue = new TextField(); NativeSelect<String> filterOrigin = new NativeSelect<>(null, origins); filterProperty.setPlaceholder("filter by key..."); filterProperty.addValueChangeListener(e -> updateProperties(e.getValue(), filterValue.getValue(), filterOrigin.getValue())); filterProperty.setValueChangeMode(ValueChangeMode.LAZY); filterProperty.focus(); filterProperty.setSizeFull(); filterValue.setPlaceholder("filter by value..."); filterValue.addValueChangeListener(e -> updateProperties(filterProperty.getValue(), e.getValue(), filterOrigin.getValue())); filterValue.setValueChangeMode(ValueChangeMode.LAZY); filterValue.setSizeFull(); filterOrigin.addValueChangeListener(e -> updateProperties(filterProperty.getValue(), filterValue.getValue(), e.getValue())); filterOrigin.setSizeFull(); // Header row HeaderRow filterRow = grid.addHeaderRowAt(grid.getHeaderRowCount()); filterRow.getCell(propertyColumn).setComponent(filterProperty); filterRow.getCell(valueColumn).setComponent(filterValue); filterRow.getCell(originColumn).setComponent(filterOrigin); }
@Override public void enter(ViewChangeEvent event) { pageHelper.setErrorHandler(this); this.removeAllComponents(); // Get application int appId = Integer.parseInt(event.getParameters()); Application app = pageHelper.getApp(appId); // Get loggers config Optional<Loggers> loggers = getLoggers(app); if(loggers.isPresent()) { // Display loggers in a grid grid = new Grid<>(LoggerGridRow.class); grid.removeAllColumns(); Column<LoggerGridRow, String> nameColumn = grid.addColumn(LoggerGridRow::getName) .setCaption("Name") .setExpandRatio(2); grid.addComponentColumn(logger -> { NativeSelect<String> levelsDropdown = new NativeSelect<>(null, loggers.get().getLevels()); levelsDropdown.setEmptySelectionAllowed(false); levelsDropdown.setSelectedItem(logger.getLevel()); // on selected level levelsDropdown.addValueChangeListener(value -> { // change logger level loggersService.changeLevel(app, logger.getName(), value.getValue()); // refresh data in grid (several loggers might have been impacted) updateLoggers(app); Notification.show( String.format("Logger %s level changed to %s", logger.getName(), value.getValue()) , Notification.Type.TRAY_NOTIFICATION); }); return levelsDropdown; }) .setCaption("Level") .setExpandRatio(1); grid.setSizeFull(); grid.setRowHeight(40); grid.setItems(loggersRows); grid.sort(nameColumn); // Filter grid by logger name filterInput = new TextField(); filterInput.setPlaceholder("filter by logger name..."); filterInput.addValueChangeListener(e -> filterLoggers(e.getValue())); filterInput.setValueChangeMode(ValueChangeMode.LAZY); filterInput.focus(); filterInput.setSizeFull(); // Header row HeaderRow filterRow = grid.addHeaderRowAt(grid.getHeaderRowCount()); filterRow.getCell(nameColumn).setComponent(filterInput); this.addComponent(new PageHeader(app, "Loggers")); this.addComponent(new Label("Changing a level will update one/many logger(s) level(s)")); this.addComponent(grid); } else { this.addComponent(new PageHeader(app, "Loggers")); this.addComponent(new Label(String.format("Failed to call %s<br />This endpoint is available since Spring Boot 1.5", app.endpoints().loggers()), ContentMode.HTML)); } }
/** * Sets up the editability of the column * * @param grid * @param definition * @param column */ @SuppressWarnings("unchecked") protected <ITEM> void setupEditableColumn(Grid<ITEM> grid, ColumnDefinition definition, Column<ITEM, Object> column) { ResolvableType editorProviderType = ResolvableType.forClassWithGenerics(BeanGridEditorComponentProvider.class, definition.getPropertyType()); List<String> editorProviderNames = Arrays.asList(appContext.getBeanNamesForType(editorProviderType)); if (editorProviderNames.isEmpty()) { throw new ColumnDefinitionException("Could not find editor component provider for " + definition.getPropertyType().getSimpleName() + ", please implement appropriate " + BeanGridEditorComponentProvider.class.getSimpleName() + " as Spring bean."); } if (editorProviderNames.size() > 1) { throw new ColumnDefinitionException( "More than one component provider exists for " + definition.getPropertyType().getSimpleName() + ": " + editorProviderNames.stream().collect(Collectors.joining(", "))); } BeanGridEditorComponentProvider<Object> editorProvider = appContext .getBean(editorProviderNames.iterator().next(), BeanGridEditorComponentProvider.class); HasValue<?> editorComponent = editorProvider.provideEditorComponent(definition); ((AbstractComponent) editorComponent).setData(definition); BindingBuilder<ITEM, Object> bindingBuilder = (BindingBuilder<ITEM, Object>) grid.getEditor().getBinder() .forField(editorComponent); bindingBuilder = bindingBuilder.withNullRepresentation(editorComponent.getEmptyValue()); if (editorProvider.requiresConversion()) { Converter<Object, Object> converter = (Converter<Object, Object>) editorProvider.asConvertable() .getConverter(); bindingBuilder = bindingBuilder.withConverter(converter); } Binding<ITEM, ?> binding = bindingBuilder.bind((item) -> { return invokeRead(definition.getReadMethod(), item); }, (item, value) -> { invokeWrite(definition, item, value); }); column.setEditorBinding(binding); column.setEditable(true); }
@Test public void test() { Person p1 = new Person(1, "John", LocalDate.of(1990, Month.JANUARY, 2)); Person p2 = new Person(1, "George", LocalDate.of(1991, Month.JUNE, 19)); Person p3 = new Person(1, "Tim", LocalDate.of(1995, Month.APRIL, 7)); List<Person> persons = Arrays.asList(p1, p2, p3); ListDataProvider<Person> dataProvider = DataProvider.ofCollection(persons); FGrid<Person> grid = new FGrid<Person>(Person.class).withColumns("name", "birthday") .withSelectionMode(SelectionMode.SINGLE) .withFrozenColumnCount(1) .withHeaderVisible(false) .withFooterVisible(false) .withRowHeight(25) .withColumnReorderingAllowed(false) .withHeightByRows(12) .withDataProvider(dataProvider) .withSort("birthday", SortDirection.DESCENDING); grid.withItemClickListener(event -> grid.setDetailsVisible(event.getItem(), !grid.isDetailsVisible(event.getItem()))) .withDetailsGenerator(person -> new Label(person.getName())) .withSortListener(event -> System.out.println("sort changed")); Column<Person, ?> birthdayColumn = grid.getColumn("birthday"); assertNotNull(grid.getColumn("name")); assertNotNull(birthdayColumn); assertTrue(grid.getSelectionModel() instanceof SingleSelectionModel); assertEquals(1, grid.getFrozenColumnCount()); assertFalse(grid.isHeaderVisible()); assertFalse(grid.isFooterVisible()); assertFalse(grid.isColumnReorderingAllowed()); assertEquals(25, grid.getRowHeight(), 0); assertEquals(12, grid.getHeightByRows(), 0); assertEquals(dataProvider, grid.getDataProvider()); assertEquals(birthdayColumn, grid.getSortOrder().get(0).getSorted()); assertEquals(SortDirection.DESCENDING, grid.getSortOrder().get(0).getDirection()); assertEquals(1, grid.getListeners(ItemClick.class).size()); assertEquals(1, grid.getListeners(SortEvent.class).size()); }
protected HtmlButtonRendererClickEvent(Grid source, Object item, Column column, MouseEventDetails mouseEventDetails) { super(source, mouseEventDetails); this.item = item; this.column = column; }
protected DeleteRendererClickEvent(Grid source, Object itemId, Column column, MouseEventDetails mouseEventDetails) { super(source, mouseEventDetails); this.itemId = itemId; this.column = column; }
public DemoContentLayout() { final SelectGrid<TestObject> grid = new SelectGrid<>(); grid.addColumn(TestObject::getFoo).setCaption("Foo"); grid.addColumn(TestObject::getBar, new NumberRenderer()).setCaption("Bar"); grid.addColumn(TestObject::getKm, new NumberRenderer()).setCaption("KM"); grid.setHeightByRows(10); grid.setHeightMode(HeightMode.ROW); // Show it in the middle of the screen setStyleName("demoContentLayout"); setSizeFull(); addComponent(grid); setComponentAlignment(grid, Alignment.MIDDLE_CENTER); final TableSelectionModel<TestObject> tableSelect = new TableSelectionModel<>(); grid.setSelectionModel(tableSelect); tableSelect.setMode(TableSelectionMode.CTRL); HorizontalLayout tableSelectionControls = new HorizontalLayout(); tableSelectionControls.setCaption("Table Selection Controls"); // Controls for testing different TableSelectionModes for (final TableSelectionMode t : TableSelectionMode.values()) { tableSelectionControls.addComponent(new Button(t.toString(), e -> tableSelect.setMode(t))); } addComponent(tableSelectionControls); // TODO: PagingDataProvider PagedDataProvider<TestObject, SerializablePredicate<TestObject>> dataProvider = new PagedDataProvider<>( DataProvider.ofCollection(TestObject.generateTestData(995))); grid.setDataProvider(dataProvider); PagingControls pagingControls = dataProvider.getPagingControls(); HorizontalLayout pages = new HorizontalLayout(); pages.setCaption("Paging controls"); pages.addComponent(new Button("First", e -> pagingControls.setPageNumber(0))); pages.addComponent(new Button("Previous", e -> pagingControls.previousPage())); pages.addComponent(new Button("Next", e -> pagingControls.nextPage())); pages.addComponent(new Button("Last", e -> pagingControls.setPageNumber(pagingControls.getPageCount() - 1))); VerticalLayout controls = new VerticalLayout(); controls.addComponents(tableSelectionControls, pages); controls.setWidth("100%"); controls.setHeightUndefined(); controls.setComponentAlignment(tableSelectionControls, Alignment.MIDDLE_CENTER); controls.setComponentAlignment(pages, Alignment.BOTTOM_CENTER); addComponent(controls); setComponentAlignment(controls, Alignment.MIDDLE_CENTER); grid.getEditor().setEnabled(true); for (Column<TestObject, ?> c : grid.getColumns()) { c.setHidable(true); } }
public Column<T, ?> getColumn() { return column; }
@Override public String getHeaderValue(Object column) { return grid.getDefaultHeaderRow().getCell((Column<?,?>)column).getText(); }
protected TableColumnManager configureSaveColumnWidths(final Grid grid, String tableId) { grid.setData(tableId); final String baseWidthKey = tableId + "_" + COLUMN_WIDTH; final String baseVisableKey = tableId + "_" + COLUMN_VISABLE; final String keyStub = tableId + "_order"; try { setupGridColumnSizing(grid, baseWidthKey); setupGridColumnVisibility(grid, baseVisableKey); setupGridColumnReordering(grid, keyStub); String keySorting = tableId + "_sort"; setupGridSorting(grid, keySorting); } catch (Exception e) { logger.error(e, e); } return new TableColumnManager() { @Override public void reset() { for (Column col : grid.getColumns()) { col.setWidthUndefined(); getConfigDelegate().deleteValuesLike(getPortal(), baseWidthKey + col.getPropertyId()); } } }; }
private void setColumnWidth(final Column column, final double width) { // Avoid IllegalArgumentException if proposed width ends up being < 0 column.setWidth(width > 0 ? width : 0); }
/** * Sets a new column order for the grid. All columns which are not ordered * here will remain in the order they were before as the last columns of * grid. * * @param columns * the columns in the order they should be * @return this for method chaining * @see Grid#setColumnOrder(Column...) */ @SuppressWarnings("unchecked") public default THIS withColumnOrder(Column<ITEM, ?>... columns) { ((Grid<ITEM>) this).setColumnOrder(columns); return (THIS) this; }
/** * Sort this Grid in ascending order by a specified column. * * @param column * a column to sort against * @return this for method chaining * @see Grid#sort(Column) */ @SuppressWarnings("unchecked") public default THIS withSort(Column<ITEM, ?> column) { ((Grid<ITEM>) this).sort(column); return (THIS) this; }
/** * Sort this Grid in user-specified direction by a column. * * @param column * a column to sort against * @param direction * a sort order value (ascending/descending) * @return this for method chaining * @see Grid#sort(Column, SortDirection) */ @SuppressWarnings("unchecked") public default THIS withSort(Column<ITEM, ?> column, SortDirection direction) { ((Grid<ITEM>) this).sort(column, direction); return (THIS) this; }
/** * Set the column that displays the hierarchy of this grid's data. By * default the hierarchy will be displayed in the first column. * <p> * Setting a hierarchy column by calling this method also sets the column to * be visible and not hidable. * <p> * <strong>Note:</strong> Changing the Renderer of the hierarchy column is * not supported. * * @param column * the column to use for displaying hierarchy * @return this for method chaining * @see TreeGrid#setHierarchyColumn(Grid.Column) */ @SuppressWarnings("unchecked") public default THIS withHierarchyColumn(Column<ITEM, ?> column) { ((TreeGrid<ITEM>) this).setHierarchyColumn(column); return (THIS) this; }
/** * Returns the {@link Column} where the click event originated. * * @return the column of the click event */ public Column getColumn() { return column; }