Example usage for com.vaadin.ui Grid getSelectionModel

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

Introduction

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

Prototype

public GridSelectionModel<T> getSelectionModel() 

Source Link

Document

Returns the selection model for this grid.

Usage

From source file:annis.gui.admin.CorpusAdminPanel.java

License:Apache License

public CorpusAdminPanel() {
    corpusContainer.setBeanIdProperty("name");

    final Grid corporaGrid = new Grid(corpusContainer);
    corporaGrid.setSizeFull();/*from   w w w .  ja  va 2  s  .com*/
    corporaGrid.setSelectionMode(Grid.SelectionMode.MULTI);
    corporaGrid.setColumns("name", "textCount", "tokenCount", "sourcePath");

    corporaGrid.getColumn("textCount").setHeaderCaption("Texts");
    corporaGrid.getColumn("tokenCount").setHeaderCaption("Tokens");
    corporaGrid.getColumn("sourcePath").setHeaderCaption("Source Path");

    Button btDelete = new Button("Delete selected");
    btDelete.addClickListener(new Button.ClickListener() {

        @Override
        public void buttonClick(Button.ClickEvent event) {
            Set<String> selection = new TreeSet<>();
            for (Object o : corporaGrid.getSelectedRows()) {
                selection.add((String) o);
            }
            corporaGrid.getSelectionModel().reset();
            if (!selection.isEmpty()) {

                for (CorpusListView.Listener l : listeners) {
                    l.deleteCorpora(selection);
                }
            }
        }
    });

    VerticalLayout layout = new VerticalLayout(btDelete, corporaGrid);
    layout.setSizeFull();
    layout.setExpandRatio(corporaGrid, 1.0f);
    layout.setSpacing(true);
    layout.setMargin(new MarginInfo(true, false, false, false));

    layout.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);

    setContent(layout);
    setSizeFull();
}

From source file:com.mycompany.controller.initUImethods.java

public void createButt(String day, Grid.MultiSelectionModel selectionOfGivenDay, Grid gridOfGivenDay,
        Grid.FooterRow footer) {//from   w  ww .  jav a  2  s  .c  o m
    Button buttonThisDay = new Button("Add to cart", new Button.ClickListener() { //anonim inner class

        @Override
        public void buttonClick(Button.ClickEvent e) {
            for (Object itemId : selectionOfGivenDay.getSelectedRows()) {
                Property nameOfGiven = gridOfGivenDay.getContainerDataSource().getContainerProperty(itemId,
                        "name");
                Property priceOfGiven = gridOfGivenDay.getContainerDataSource().getContainerProperty(itemId,
                        "price");
                Property quantityOfGiven = gridOfGivenDay.getContainerDataSource().getContainerProperty(itemId,
                        "quantity");
                int price = Integer.parseInt(priceOfGiven.getValue().toString());
                int quan = Integer.parseInt(quantityOfGiven.getValue().toString());
                cartItems.add(new CartObject(day, nameOfGiven.getValue().toString(), price, quan,
                        Days.valueOf(day).getPriority()));
            }

            cart.getContainerDataSource().removeAllItems(); //sorbarendezs miatt, nem a legjobb de elmegy
            sum = 0;
            gridOfGivenDay.getSelectionModel().reset();
            cartItems.sort(Comparator.comparing(CartObject::getPriority));

            for (CartObject cartItem : cartItems) {
                cart.addRow(cartItem.getDay(), cartItem.getFoodName(), cartItem.getPrice(), cartItem.getQuan());
                sum += cartItem.getPrice() * cartItem.getQuan();
            }
            footer.getCell("Mennyisg").setText(Integer.toString(sum));
        }
    });

    gridOfGivenDay.getFooterRow(0).getCell("name").setComponent(buttonThisDay);
    buttonThisDay.setStyleName(ValoTheme.BUTTON_FRIENDLY);
}

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

License:Apache License

private void init() {
    setSizeFull();/*from   w w  w  .j  ava 2  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:net.sourceforge.javydreamercsw.validation.manager.web.admin.AdminScreenProvider.java

License:Apache License

private Component displayIssueTypes() {
    VerticalLayout vl = new VerticalLayout();
    Grid grid = new Grid(TRANSLATOR.translate(ISSUE_TYPE));
    BeanItemContainer<IssueType> types = new BeanItemContainer<>(IssueType.class);
    types.addAll(new IssueTypeJpaController(DataBaseManager.getEntityManagerFactory()).findIssueTypeEntities());
    grid.setContainerDataSource(types);/* ww w . j a v a  2s.co m*/
    grid.setSelectionMode(SelectionMode.SINGLE);
    grid.setColumns("typeName", DESC);
    Grid.Column name = grid.getColumn("typeName");
    name.setHeaderCaption(TRANSLATOR.translate("general.name"));
    name.setConverter(new TranslationConverter());
    Grid.Column desc = grid.getColumn(DESC);
    desc.setHeaderCaption(TRANSLATOR.translate("general.description"));
    desc.setConverter(new TranslationConverter());
    grid.setSizeFull();
    vl.addComponent(grid);
    grid.setHeightMode(HeightMode.ROW);
    grid.setHeightByRows(types.size() > 5 ? 5 : types.size());
    //Menu
    HorizontalLayout hl = new HorizontalLayout();
    Button add = new Button(TRANSLATOR.translate("general.create"));
    add.addClickListener(listener -> {
        VMWindow w = new VMWindow();
        w.setContent(new IssueTypeComponent(new IssueType(), true));
        ((VMUI) UI.getCurrent()).addWindow(w);
        w.addCloseListener(l -> {
            ((VMUI) UI.getCurrent()).updateScreen();
        });
    });
    hl.addComponent(add);
    Button delete = new Button(TRANSLATOR.translate("general.delete"));
    delete.setEnabled(false);
    delete.addClickListener(listener -> {
        IssueType selected = (IssueType) ((SingleSelectionModel) grid.getSelectionModel()).getSelectedRow();
        if (selected != null && selected.getId() >= 1000) {
            try {
                new IssueTypeJpaController(DataBaseManager.getEntityManagerFactory()).destroy(selected.getId());
                ((VMUI) UI.getCurrent()).updateScreen();
            } catch (IllegalOrphanException | NonexistentEntityException ex) {
                LOG.log(Level.SEVERE, null, ex);
                Notification.show(TRANSLATOR.translate(DELETE_ERROR), TRANSLATOR.translate(DELETE_ERROR),
                        Notification.Type.ERROR_MESSAGE);
            }
        }
    });
    hl.addComponent(delete);
    vl.addComponent(hl);
    grid.addSelectionListener(event -> { // Java 8
        // Get selection from the selection model
        IssueType selected = (IssueType) ((SingleSelectionModel) grid.getSelectionModel()).getSelectedRow();
        //Only delete custom ones.
        delete.setEnabled(selected != null && selected.getId() >= 1000);
    });
    return vl;
}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.admin.AdminScreenProvider.java

License:Apache License

private Component displayIssueResolutions() {
    VerticalLayout vl = new VerticalLayout();
    Grid grid = new Grid(TRANSLATOR.translate(ISSUE_RESOLUTION));
    BeanItemContainer<IssueResolution> types = new BeanItemContainer<>(IssueResolution.class);
    types.addAll(new IssueResolutionJpaController(DataBaseManager.getEntityManagerFactory())
            .findIssueResolutionEntities());
    grid.setContainerDataSource(types);//w  ww  . ja va  2s .c  o m
    grid.setSelectionMode(SelectionMode.SINGLE);
    grid.setColumns(NAME);
    Grid.Column name = grid.getColumn(NAME);
    name.setHeaderCaption(TRANSLATOR.translate("general.name"));
    name.setConverter(new TranslationConverter());
    grid.setSizeFull();
    vl.addComponent(grid);
    grid.setHeightMode(HeightMode.ROW);
    grid.setHeightByRows(types.size() > 5 ? 5 : types.size());
    //Menu
    HorizontalLayout hl = new HorizontalLayout();
    Button add = new Button(TRANSLATOR.translate("general.create"));
    add.addClickListener(listener -> {
        VMWindow w = new VMWindow();
        w.setContent(new IssueResolutionComponent(new IssueResolution(), true));
        ((VMUI) UI.getCurrent()).addWindow(w);
        w.addCloseListener(l -> {
            ((VMUI) UI.getCurrent()).updateScreen();
        });
    });
    hl.addComponent(add);
    Button delete = new Button(TRANSLATOR.translate("general.delete"));
    delete.setEnabled(false);
    delete.addClickListener(listener -> {
        IssueResolution selected = (IssueResolution) ((SingleSelectionModel) grid.getSelectionModel())
                .getSelectedRow();
        if (selected != null && selected.getId() >= 1000) {
            try {
                new IssueResolutionJpaController(DataBaseManager.getEntityManagerFactory())
                        .destroy(selected.getId());
                ((VMUI) UI.getCurrent()).updateScreen();
            } catch (IllegalOrphanException | NonexistentEntityException ex) {
                LOG.log(Level.SEVERE, null, ex);
                Notification.show(TRANSLATOR.translate(DELETE_ERROR), TRANSLATOR.translate(DELETE_ERROR),
                        Notification.Type.ERROR_MESSAGE);
            }
        }
    });
    hl.addComponent(delete);
    vl.addComponent(hl);
    grid.addSelectionListener(event -> { // Java 8
        // Get selection from the selection model
        IssueResolution selected = (IssueResolution) ((SingleSelectionModel) grid.getSelectionModel())
                .getSelectedRow();
        //Only delete custom ones.
        delete.setEnabled(selected != null && selected.getId() >= 1000);
    });
    return vl;
}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.admin.AdminScreenProvider.java

License:Apache License

private Component displayRequirementTypes() {
    VerticalLayout vl = new VerticalLayout();
    Grid grid = new Grid(TRANSLATOR.translate(REQUIREMENT_TYPE));
    BeanItemContainer<RequirementType> types = new BeanItemContainer<>(RequirementType.class);
    types.addAll(new RequirementTypeJpaController(DataBaseManager.getEntityManagerFactory())
            .findRequirementTypeEntities());
    grid.setContainerDataSource(types);//  ww  w . ja  v  a  2  s. c  om
    grid.setSelectionMode(SelectionMode.SINGLE);
    grid.setColumns(NAME, DESC);
    Grid.Column name = grid.getColumn(NAME);
    name.setHeaderCaption(TRANSLATOR.translate("general.name"));
    name.setConverter(new TranslationConverter());
    Grid.Column desc = grid.getColumn(DESC);
    desc.setHeaderCaption(TRANSLATOR.translate("general.description"));
    desc.setConverter(new TranslationConverter());
    grid.setSizeFull();
    vl.addComponent(grid);
    grid.setHeightMode(HeightMode.ROW);
    grid.setHeightByRows(types.size() > 5 ? 5 : types.size());
    //Menu
    HorizontalLayout hl = new HorizontalLayout();
    Button add = new Button(TRANSLATOR.translate("general.create"));
    add.addClickListener(listener -> {
        VMWindow w = new VMWindow();
        w.setContent(new RequirementTypeComponent(new RequirementType(), true));
        ((VMUI) UI.getCurrent()).addWindow(w);
        w.addCloseListener(l -> {
            ((VMUI) UI.getCurrent()).updateScreen();
        });
    });
    hl.addComponent(add);
    Button delete = new Button(TRANSLATOR.translate("general.delete"));
    delete.setEnabled(false);
    delete.addClickListener(listener -> {
        RequirementType selected = (RequirementType) ((SingleSelectionModel) grid.getSelectionModel())
                .getSelectedRow();
        if (selected != null && selected.getId() >= 1000) {
            try {
                new RequirementTypeJpaController(DataBaseManager.getEntityManagerFactory())
                        .destroy(selected.getId());
                ((VMUI) UI.getCurrent()).updateScreen();
            } catch (IllegalOrphanException | NonexistentEntityException ex) {
                LOG.log(Level.SEVERE, null, ex);
                Notification.show(TRANSLATOR.translate(DELETE_ERROR), TRANSLATOR.translate(DELETE_ERROR),
                        Notification.Type.ERROR_MESSAGE);
            }
        }
    });
    hl.addComponent(delete);
    vl.addComponent(hl);
    grid.addSelectionListener(event -> { // Java 8
        // Get selection from the selection model
        RequirementType selected = (RequirementType) ((SingleSelectionModel) grid.getSelectionModel())
                .getSelectedRow();
        //Only delete custom ones.
        delete.setEnabled(selected != null && selected.getId() >= 1000);
    });
    return vl;
}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.notification.NotificationScreenProvider.java

License:Apache License

@Override
public Component getContent() {
    VerticalLayout vs = new VerticalLayout();
    //On top put a list of notifications
    BeanItemContainer<Notification> container = new BeanItemContainer<>(Notification.class);
    ValidationManagerUI.getInstance().getUser().getNotificationList().forEach(n -> {
        container.addBean(n);/* w ww  .  j  a va 2 s  . c om*/
    });
    //        Unable to use VerticalSplitPanel as I hoped.
    //        See: https://github.com/vaadin/framework/issues/9460
    //        VerticalSplitPanel vs = new VerticalSplitPanel();
    //        vs.setSplitPosition(25, Sizeable.Unit.PERCENTAGE);
    TextArea text = new TextArea(TRANSLATOR.translate("general.text"));
    text.setWordwrap(true);
    text.setReadOnly(true);
    text.setSizeFull();
    Grid grid = new Grid(TRANSLATOR.translate("general.notifications"), container);
    grid.setColumns("notificationType", "author", "creationDate", "archieved");
    if (container.size() > 0) {
        grid.setHeightMode(HeightMode.ROW);
        grid.setHeightByRows(container.size() > 5 ? 5 : container.size());
    }
    GridCellFilter filter = new GridCellFilter(grid);
    filter.setBooleanFilter("archieved",
            new GridCellFilter.BooleanRepresentation(VaadinIcons.CHECK, TRANSLATOR.translate("general.yes")),
            new GridCellFilter.BooleanRepresentation(VaadinIcons.CLOSE, TRANSLATOR.translate("general.no")));
    filter.setDateFilter("creationDate",
            new SimpleDateFormat(VMSettingServer.getSetting("date.format").getStringVal()), true);
    grid.sort("creationDate");
    Column nt = grid.getColumn("notificationType");
    nt.setHeaderCaption(TRANSLATOR.translate("notification.type"));
    nt.setConverter(new Converter<String, NotificationType>() {
        @Override
        public NotificationType convertToModel(String value, Class<? extends NotificationType> targetType,
                Locale locale) throws Converter.ConversionException {
            for (NotificationType n : new NotificationTypeJpaController(
                    DataBaseManager.getEntityManagerFactory()).findNotificationTypeEntities()) {
                if (Lookup.getDefault().lookup(InternationalizationProvider.class).translate(n.getTypeName())
                        .equals(value)) {
                    return n;
                }
            }
            return null;
        }

        @Override
        public String convertToPresentation(NotificationType value, Class<? extends String> targetType,
                Locale locale) throws Converter.ConversionException {
            return Lookup.getDefault().lookup(InternationalizationProvider.class)
                    .translate(value.getTypeName());
        }

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

        @Override
        public Class<String> getPresentationType() {
            return String.class;
        }
    });
    Column author = grid.getColumn("author");
    author.setConverter(new UserToStringConverter());
    author.setHeaderCaption(TRANSLATOR.translate("notification.author"));
    Column creation = grid.getColumn("creationDate");
    creation.setHeaderCaption(TRANSLATOR.translate("creation.time"));
    Column archive = grid.getColumn("archieved");
    archive.setHeaderCaption(TRANSLATOR.translate("general.archived"));
    archive.setConverter(new Converter<String, Boolean>() {
        @Override
        public Boolean convertToModel(String value, Class<? extends Boolean> targetType, Locale locale)
                throws Converter.ConversionException {
            return value.equals(TRANSLATOR.translate("general.yes"));
        }

        @Override
        public String convertToPresentation(Boolean value, Class<? extends String> targetType, Locale locale)
                throws Converter.ConversionException {
            return value ? TRANSLATOR.translate("general.yes") : TRANSLATOR.translate("general.no");
        }

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

        @Override
        public Class<String> getPresentationType() {
            return String.class;
        }
    });
    grid.setSelectionMode(SelectionMode.SINGLE);
    grid.setSizeFull();
    ContextMenu menu = new ContextMenu(grid, true);
    menu.addItem(TRANSLATOR.translate("notification.mark.unread"), (MenuItem selectedItem) -> {
        Object selected = ((SingleSelectionModel) grid.getSelectionModel()).getSelectedRow();
        if (selected != null) {
            NotificationServer ns = new NotificationServer((Notification) selected);
            ns.setAcknowledgeDate(null);
            try {
                ns.write2DB();
                ((VMUI) UI.getCurrent()).updateScreen();
                ((VMUI) UI.getCurrent()).showTab(getComponentCaption());
            } catch (VMException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
    });
    menu.addItem(TRANSLATOR.translate("notification.archive"), (MenuItem selectedItem) -> {
        Object selected = ((SingleSelectionModel) grid.getSelectionModel()).getSelectedRow();
        if (selected != null) {
            NotificationServer ns = new NotificationServer((Notification) selected);
            ns.setArchieved(true);
            try {
                ns.write2DB();
                ((VMUI) UI.getCurrent()).updateScreen();
                ((VMUI) UI.getCurrent()).showTab(getComponentCaption());
            } catch (VMException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
    });
    grid.addSelectionListener(selectionEvent -> {
        // Get selection from the selection model
        Object selected = ((SingleSelectionModel) grid.getSelectionModel()).getSelectedRow();
        if (selected != null) {
            text.setReadOnly(false);
            Notification n = (Notification) selected;
            text.setValue(n.getContent());
            text.setReadOnly(true);
            if (n.getAcknowledgeDate() != null) {
                try {
                    //Mark as read
                    NotificationServer ns = new NotificationServer((Notification) n);
                    ns.setAcknowledgeDate(new Date());
                    ns.write2DB();
                } catch (VMException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }
            }
        }
    });
    vs.addComponent(grid);
    vs.addComponent(text);
    vs.setSizeFull();
    vs.setId(getComponentCaption());
    return vs;
}

From source file:org.tylproject.vaadin.addon.fields.zoom.GridZoomDialog.java

License:Apache License

private void setupDialog(Grid grid) {
    if (!(grid.getSelectionModel() instanceof Grid.SingleSelectionModel)) {
        throw new AssertionError("Selection mode must be " + Grid.SelectionMode.SINGLE.getClass() + ", "
                + grid.getSelectionModel().getClass() + " was given");
    }//  ww w  . j a v a  2 s .c om

    addComponent(grid);
    setExpandRatio(getGrid(), 1f);
    setSizeFull();
}

From source file:qbic.vaadincomponents.InputFilesComponent.java

License:Open Source License

/**
 * updates workflow parameters with the currently selected datasets and databases. Be aware that
 * it is not checked, whether the correct workflow is given as parameter
 * /*ww w .  j a v  a2s . c  om*/
 * @param wf
 * @return false if nothing is selected for some tabs or wf is null or wf is empty
 */
public boolean updateWorkflow(Workflow wf, WorkflowViewController controller) {
    if (wf == null || wf.getData() == null || wf.getData().getData() == null
            || wf.getData().getData().isEmpty())
        return false;

    java.util.Iterator<Component> i = inputFileForm.iterator();
    InputList inpList = wf.getData();
    while (i.hasNext()) {
        Tab tab = inputFileForm.getTab(i.next());

        HorizontalLayout current = (HorizontalLayout) tab.getComponent();
        java.util.Iterator<Component> j = current.iterator();
        while (j.hasNext()) {
            Grid currentGrid = (Grid) j.next();

            String caption = tab.getCaption();

            if (currentGrid.getSelectionModel() instanceof SingleSelectionModel) {
                Object selectionSingle = currentGrid.getSelectedRow();
                // Quick solution
                // TODO Fixed?!
                // if (selectionSingle == null) {
                // if (caption.equals("InputFiles.1.Germline Mutations")
                // || caption.equals("InputFiles.1.bam")) {
                // continue;
                // } else {
                if (selectionSingle == null) {
                    if (wf.getData().getData().get(caption).isRequired()) {
                        helpers.Utils.Notification("Missing input file(s)",
                                "Nothing selected for required input file category" + caption, "error");
                        return false;
                    } else {
                        continue;
                    }
                }

                else {
                    if (selectionSingle instanceof FastaBean) {
                        FastaBean selectedBean = (FastaBean) selectionSingle;
                        inpList.getData().get(caption).setValue(selectedBean.getPath());
                    } else {
                        DatasetBean selectedBean = (DatasetBean) selectionSingle;
                        try {
                            inpList.getData().get(caption)
                                    .setValue(controller.getDatasetsNfsPath(selectedBean));
                        } catch (Exception e) {
                            LOGGER.error("could not retrieve nfs path. Using datasetbeans getfullpath instead. "
                                    + e.getMessage(), e.getStackTrace());
                            inpList.getData().get(caption).setValue(selectedBean.getFullPath());
                        }
                    }
                }

            } else {
                Collection<Object> selectionMulti = currentGrid.getSelectedRows();
                // if ((selectionMulti == null || selectionMulti.isEmpty())
                // && (!caption.equals("InputFiles.1.fastq"))) {
                if ((selectionMulti == null || selectionMulti.isEmpty())) {

                    if (wf.getData().getData().get(caption).isRequired()) {
                        helpers.Utils.Notification("Missing input file(s)",
                                "Nothing selected for required input file(s) category" + caption, "warning");
                        return false;
                    }

                    else {
                        continue;
                    }
                } else {

                    List<String> selectedPaths = new ArrayList<String>();

                    for (Object o : selectionMulti) {
                        DatasetBean selectedBean = (DatasetBean) o;
                        try {
                            selectedPaths.add(controller.getDatasetsNfsPath(selectedBean));
                        } catch (Exception e) {
                            LOGGER.error("could not retrieve nfs path. Using datasetbeans getfullpath instead. "
                                    + e.getMessage(), e.getStackTrace());
                            selectedPaths.add(selectedBean.getFullPath());
                        }
                    }
                    inpList.getData().get(caption).setValue(selectedPaths);
                }
            }
        }
    }
    return true;
}