Example usage for com.vaadin.ui Tree addItemClickListener

List of usage examples for com.vaadin.ui Tree addItemClickListener

Introduction

In this page you can find the example usage for com.vaadin.ui Tree addItemClickListener.

Prototype

public Registration addItemClickListener(ItemClickListener<T> listener) 

Source Link

Document

Adds an item click listener.

Usage

From source file:com.wintindustries.pfserver.interfaces.view.dashboard.DashboardMenu.java

private Component buildFolderTree() {

    CssLayout treeLayout = new CssLayout();
    treeLayout.setWidth("100%");
    if (treeLayout.getComponentCount() > 0) {
        treeLayout.removeAllComponents();
    }//from   w  w  w .j  a v  a 2 s  .c  om

    System.out.println("Init Dataasource");

    for (PFDataSource source : PFCore.core.getDataSources()) {
        System.out.println("NEW TREE");

        Label label = new Label(source.getName(), ContentMode.HTML);
        label.setPrimaryStyleName("valo-menu-subtitle");
        label.addStyleName("h4");

        label.setSizeUndefined();
        treeLayout.addComponent(label);
        //      label.setIcon(FontAwesome.LAPTOP);
        treeLayout.addStyleName("valo-menuitems");

        Tree tree = new Tree();
        //tree.setIcon(FontAwesome.LAPTOP);
        // tree.setWidth("100%");

        // container.setItemSorter(new l);

        source.Session().OpenSession();
        source.Session().getSession().beginTransaction();
        source.Session().getSession().getTransaction().setTimeout(4);

        System.out.println(": " + source.getDatabase().getSessionManager());

        Set<PFFolder> rootFolders = PFLocation.getRootDirectoriesFromDatabase(source.getDatabase());

        System.out.println(": " + source.getDatabase().getSessionManager());

        final PFFolderProxyContainer container = new PFFolderProxyContainer(rootFolders, source);

        container.setSortAlphabetic(true);
        tree.setContainerDataSource(container);
        tree.setItemCaptionMode(AbstractSelect.ItemCaptionMode.PROPERTY);
        tree.setItemCaptionPropertyId("Name");
        tree.setItemIconPropertyId("Icon");

        ItemClickListener treeclick;
        treeclick = new ItemClickListener() {

            @Override
            public void itemClick(final ItemClickEvent event) {

                //  Notification note = new Notification("Notificaton", event.getItemId().toString(), Notification.Type.ERROR_MESSAGE);
                // note.show(Page.getCurrent());
                PFFolderProxy proxyFolder = (PFFolderProxy) event.getItemId();
                MyUI.getPFNavigator().navigateTo(MyUI.PAGE_FOLDERVIEW + "/" + proxyFolder.getIdentifier());
            }
        };

        tree.addItemClickListener(treeclick);

        // Allow all nodes to have children
        //   .dashboard-menu-folder-wrapper
        // all these wrappers are a hacky workaround to a Vaadin CSS glitch
        CssLayout treeWrapper = new CssLayout();
        treeWrapper.setStyleName(".dashboard-menu-folder-wrapper");
        treeWrapper.addComponent(tree);
        treeWrapper.setWidth("40px");
        tree.setWidth("800px");
        tree.setStyleName(".dashboard-menu-folder-tree");

        treeLayout.addComponent(treeWrapper);
        source.Session().getSession().getTransaction().commit();
        source.getDatabase().getSessionManager().CloseSession();
    }

    return treeLayout;

}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.component.RiskManagementComponent.java

License:Apache License

public RiskManagementComponent(Project p) {
    setSplitPosition(25, Unit.PERCENTAGE);
    setLocked(true);//  w  w  w. j av a  2  s .c  om
    Tree tree = new Tree("Test");
    tree.setSizeFull();
    tree.addItem(p);
    tree.setItemCaption(p, p.getName());
    p.getFmeaList().forEach(fmea -> {
        tree.addItem(fmea);
        tree.setItemCaption(fmea, fmea.getName());
        tree.setParent(fmea, p);
    });
    TreeTable ttable = new TreeTable("FMEA");
    ttable.addContainerProperty("Name", String.class, null);
    ttable.addContainerProperty("Hazard", String.class, null);
    ttable.addContainerProperty("Failure Mode", String.class, null);
    ttable.addContainerProperty("Cause", String.class, null);
    ttable.setSizeFull();
    tree.addItemClickListener(event -> {
        if (event.getItem() != null) {
            Item clicked = event.getItem();
            tree.select(event.getItemId());
        }
        if (tree.getValue() != null && tree.getValue() instanceof Fmea) {
            Fmea fmea = (Fmea) tree.getValue();
            fmea.getRiskCategoryList().forEach(rc -> {
                ttable.addGeneratedColumn(rc.getName(), (Table source, Object itemId, Object columnId) -> {
                    if (itemId instanceof String) {
                        String id = (String) itemId;
                        if (id.startsWith("hazard")) {
                            //We have one of our entries
                            StringTokenizer st = new StringTokenizer(id.substring(id.indexOf("-") + 1), "-");
                            FailureModeHasCauseHasRiskCategoryJpaController c = new FailureModeHasCauseHasRiskCategoryJpaController(
                                    DataBaseManager.getEntityManagerFactory());
                            FailureModeHasCauseHasRiskCategory fmhchrc = c
                                    .findFailureModeHasCauseHasRiskCategory(
                                            new FailureModeHasCauseHasRiskCategoryPK(
                                                    Integer.parseInt(st.nextToken()),
                                                    Integer.parseInt(st.nextToken()),
                                                    Integer.parseInt(st.nextToken()),
                                                    Integer.parseInt(st.nextToken()),
                                                    Integer.parseInt(st.nextToken()),
                                                    Integer.parseInt(st.nextToken()), rc.getId()));
                            if (fmhchrc != null) {
                                RiskCategory cat = fmhchrc.getRiskCategory();
                                if (cat.getCategoryEquation() != null
                                        && !cat.getCategoryEquation().trim().isEmpty()) {
                                    //Calculate based on equation
                                    Double result = Tool.evaluateEquation(fmhchrc);
                                    //Update record if result changed
                                    LOG.log(Level.FINE, "Result: {0}", result);
                                    if (result != fmhchrc.getCategoryValue()) {
                                        try {
                                            fmhchrc.setCategoryValue(result);
                                            c.edit(fmhchrc);
                                        } catch (Exception ex) {
                                            Exceptions.printStackTrace(ex);
                                            return new Label("Error!");
                                        }
                                    }
                                }
                                //Return result in label.
                                return new Label("" + fmhchrc.getCategoryValue());
                            }
                        }
                    }
                    return new Label();
                });
            });
            ttable.removeAllItems();
            fmea.getRiskItemList().forEach(item -> {
                ttable.addItem(new Object[] { item.getDescription(), null, null, null },
                        item.getRiskItemPK().getId());
                item.getRiskItemHasHazardList().forEach(rihh -> {
                    rihh.getHazardHasFailureModeList().forEach(hhfm -> {
                        hhfm.getFailureModeHasCauseList().forEach(fmhc -> {
                            String hkey = "hazard-" + item.getRiskItemPK().getId() + "-"
                                    + fmea.getFmeaPK().getId() + "-" + fmea.getFmeaPK().getProjectId() + "-"
                                    + rihh.getHazard().getId() + "-" + hhfm.getFailureMode().getId() + "-"
                                    + fmhc.getCause().getId();
                            ttable.addItem(
                                    new Object[] { null, rihh.getHazard().getName(),
                                            hhfm.getFailureMode().getName(), fmhc.getCause().getDescription() },
                                    hkey);
                            ttable.setParent(hkey, item.getRiskItemPK().getId());
                            //No children
                            ttable.setChildrenAllowed(hkey, false);
                        });
                    });
                });
            });
        }
    });
    ContextMenu contextMenu = new ContextMenu(tree, true);
    tree.addItemClickListener((ItemClickEvent event) -> {
        if (event.getButton() == MouseButton.RIGHT) {
            contextMenu.removeItems();
        }
    });
    setFirstComponent(tree);
    setSecondComponent(ttable);
    setSizeFull();
}

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

License:Apache License

private void createTree() {
    tree = new ProjectTreeComponent();
    // Set the tree in drag source mode
    tree.setDragMode(TreeDragMode.NODE);
    // Allow the tree to receive drag drops and handle them
    tree.setDropHandler(new DropHandler() {
        @Override//  www.  j  a  v a 2 s.c  om
        public AcceptCriterion getAcceptCriterion() {
            TreeDropCriterion criterion = new TreeDropCriterion() {
                @Override
                protected Set<Object> getAllowedItemIds(DragAndDropEvent dragEvent, Tree tree) {
                    HashSet<Object> allowed = new HashSet<>();
                    tree.getItemIds().stream()
                            .filter((itemId) -> (itemId instanceof Step) || (itemId instanceof Requirement))
                            .forEachOrdered((itemId) -> {
                                allowed.add(itemId);
                            });
                    return allowed;
                }
            };
            return criterion;
        }

        @Override
        public void drop(DragAndDropEvent event) {
            // Wrapper for the object that is dragged
            Transferable t = event.getTransferable();

            // Make sure the drag source is the same tree
            if (t.getSourceComponent() != tree) {
                return;
            }

            TreeTargetDetails target = (TreeTargetDetails) event.getTargetDetails();

            // Get ids of the dragged item and the target item
            Object sourceItemId = t.getData("itemId");
            Object targetItemId = target.getItemIdOver();

            LOG.log(Level.INFO, "Source: {0}", sourceItemId);
            LOG.log(Level.INFO, "Target: {0}", targetItemId);

            // On which side of the target the item was dropped
            VerticalDropLocation location = target.getDropLocation();

            HierarchicalContainer container = (HierarchicalContainer) tree.getContainerDataSource();

            if (null != location) // Drop right on an item -> make it a child
            {
                switch (location) {

                case MIDDLE:
                    if (tree.areChildrenAllowed(targetItemId)) {
                        tree.setParent(sourceItemId, targetItemId);
                    }
                    break;
                case TOP: {
                    boolean valid = false;
                    //for Steps we need to update the sequence number
                    if (sourceItemId instanceof Step && targetItemId instanceof Step) {
                        Step targetItem = (Step) targetItemId;
                        Step sourceItem = (Step) sourceItemId;
                        StepJpaController stepController = new StepJpaController(
                                DataBaseManager.getEntityManagerFactory());
                        if (targetItem.getTestCase().equals(sourceItem.getTestCase())) {
                            //Same Test Case, just re-arrange
                            LOG.info("Same Test Case!");
                            SortedMap<Integer, Step> map = new TreeMap<>();
                            targetItem.getTestCase().getStepList().forEach((s) -> {
                                map.put(s.getStepSequence(), s);
                            });
                            //Now swap the two that switched
                            swapValues(map, sourceItem.getStepSequence(), targetItem.getStepSequence());
                            //Now update the sequence numbers
                            int count = 0;
                            for (Entry<Integer, Step> entry : map.entrySet()) {
                                entry.getValue().setStepSequence(++count);
                                try {
                                    stepController.edit(entry.getValue());
                                } catch (Exception ex) {
                                    LOG.log(Level.SEVERE, null, ex);
                                }
                            }
                            valid = true;
                        } else {
                            //Diferent Test Case
                            LOG.info("Different Test Case!");
                            //                                    //Remove from source test case
                            //                                    SortedMap<Integer, Step> map = new TreeMap<>();
                            //                                    sourceItem.getTestCase().getStepList().forEach((s) -> {
                            //                                        map.put(s.getStepSequence(), s);
                            //                                    });
                            //                                    //Now swap the two that switched
                            //                                    //First we remove the one from the source Test Case
                            //                                    Step removed = map.remove(sourceItem.getStepSequence() - 1);
                            //                                    sourceItem.getTestCase().getStepList().remove(removed);
                            //                                    removed.setTestCase(targetItem.getTestCase());
                            //                                    try {
                            //                                        stepController.edit(removed);
                            //                                        tcController.edit(sourceItem.getTestCase());
                            //                                    } catch (NonexistentEntityException ex) {
                            //                                         LOG.log(Level.SEVERE, null, ex);
                            //                                    } catch (Exception ex) {
                            //                                         LOG.log(Level.SEVERE, null, ex);
                            //                                    }
                            //                                    //Now update the sequence numbers
                            //                                    int count = 0;
                            //                                    for (Entry<Integer, Step> entry : map.entrySet()) {
                            //                                        entry.getValue().setStepSequence(++count);
                            //                                        try {
                            //                                            stepController.edit(entry.getValue());
                            //                                        } catch (Exception ex) {
                            //                                             LOG.log(Level.SEVERE, null, ex);
                            //                                        }
                            //                                    }
                            //                                    //And add it to the target test Case
                            //                                    SortedMap<Integer, Step> map2 = new TreeMap<>();
                            //                                    targetItem.getTestCase().getStepList().forEach((s) -> {
                            //                                        map2.put(s.getStepSequence(), s);
                            //                                    });
                            //                                    map2.put(targetItem.getStepSequence() - 1, removed);
                            //                                    count = 0;
                            //                                    for (Entry<Integer, Step> entry : map2.entrySet()) {
                            //                                        entry.getValue().setStepSequence(++count);
                            //                                        try {
                            //                                            stepController.edit(entry.getValue());
                            //                                        } catch (Exception ex) {
                            //                                             LOG.log(Level.SEVERE, null, ex);
                            //                                        }
                            //                                    }
                            //                                    //Add it to the Test Case
                            //                                    targetItem.getTestCase().getStepList().add(removed);
                        }
                    }
                    if (valid) {
                        // Drop at the top of a subtree -> make it previous
                        Object parentId = container.getParent(targetItemId);
                        container.setParent(sourceItemId, parentId);
                        container.moveAfterSibling(sourceItemId, targetItemId);
                        container.moveAfterSibling(targetItemId, sourceItemId);
                        buildProjectTree(targetItemId);
                        updateScreen();
                    }
                    break;
                }
                case BOTTOM: {
                    // Drop below another item -> make it next
                    Object parentId = container.getParent(targetItemId);
                    container.setParent(sourceItemId, parentId);
                    container.moveAfterSibling(sourceItemId, targetItemId);
                    break;
                }
                default:
                    break;
                }
            }
        }
    });
    tree.addValueChangeListener((Property.ValueChangeEvent event) -> {
        displayObject(tree.getValue());
    });
    //Select item on right click as well
    tree.addItemClickListener((ItemClickEvent event) -> {
        if (event.getSource() == tree && event.getButton() == MouseButton.RIGHT) {
            if (event.getItem() != null) {
                Item clicked = event.getItem();
                tree.select(event.getItemId());
            }
        }
    });
    ContextMenu contextMenu = new ContextMenu(tree, true);
    tree.addItemClickListener((ItemClickEvent event) -> {
        if (event.getButton() == MouseButton.RIGHT) {
            contextMenu.removeItems();
            if (tree.getValue() instanceof Project) {
                createProjectMenu(contextMenu);
            } else if (tree.getValue() instanceof Requirement) {
                createRequirementMenu(contextMenu);
            } else if (tree.getValue() instanceof RequirementSpec) {
                createRequirementSpecMenu(contextMenu);
            } else if (tree.getValue() instanceof RequirementSpecNode) {
                createRequirementSpecNodeMenu(contextMenu);
            } else if (tree.getValue() instanceof TestProject) {
                createTestProjectMenu(contextMenu);
            } else if (tree.getValue() instanceof Step) {
                createStepMenu(contextMenu);
            } else if (tree.getValue() instanceof TestCase) {
                createTestCaseMenu(contextMenu);
            } else if (tree.getValue() instanceof String) {
                String val = (String) tree.getValue();
                if (val.startsWith("tce")) {
                    createTestExecutionMenu(contextMenu);
                } else if (val.startsWith("executions")) {
                    createExecutionsMenu(contextMenu);
                } else {
                    //We are at the root
                    createRootMenu(contextMenu);
                }
            } else if (tree.getValue() instanceof TestPlan) {
                createTestPlanMenu(contextMenu);
            } else if (tree.getValue() instanceof TestCaseExecution) {
                createTestCaseExecutionPlanMenu(contextMenu);
            } else if (tree.getValue() instanceof Baseline) {
                //                        createBaselineMenu(contextMenu);
            }
        }
    });
    tree.setImmediate(true);
    tree.expandItem(projTreeRoot);
    tree.setSizeFull();
    updateProjectList();
}

From source file:org.hip.vif.admin.groupadmin.ui.GroupContentView.java

License:Open Source License

/** View constructor
 * //from  w ww  .j ava2s  . co m
 * @param inGroup {@link Group}
 * @param inQuestions {@link GroupContentContainer}
 * @param inTask {@link AdminQuestionListTask} */
public GroupContentView(final Group inGroup, final GroupContentContainer inQuestions,
        final AdminQuestionListTask inTask) {
    task = inTask;
    final VerticalLayout lLayout = new VerticalLayout();
    setCompositionRoot(lLayout);

    final IMessages lMessages = Activator.getMessages();
    lLayout.setStyleName("vif-table"); //$NON-NLS-1$
    final String lTitle = lMessages.getFormattedMessage("ui.discussion.questions.view.title.page", //$NON-NLS-1$
            BeanWrapperHelper.getLong(GroupHome.KEY_ID, inGroup),
            BeanWrapperHelper.getString(GroupHome.KEY_NAME, inGroup));
    lLayout.addComponent(
            new Label(String.format(VIFViewHelper.TMPL_TITLE, "vif-pagetitle", lTitle), ContentMode.HTML)); //$NON-NLS-1$ //$NON-NLS-2$

    final Label lSubtitle = new Label(String.format(VIFViewHelper.TMPL_TITLE, "vif-description", //$NON-NLS-1$
            lMessages.getMessage("ui.discussion.questions.view.title.sub")), ContentMode.HTML); //$NON-NLS-1$
    lLayout.addComponent(lSubtitle);

    final Tree lTree = new Tree();
    lTree.focus();
    lTree.setContainerDataSource(inQuestions);
    lLayout.addComponent(lTree);

    for (final GroupContentWrapper lNode : inQuestions.getExpandedNodes()) {
        lTree.expandItem(lNode);
    }

    lTree.addItemClickListener(new ItemClickEvent.ItemClickListener() {
        @Override
        public void itemClick(final ItemClickEvent inEvent) {
            task.processSelection((GroupContentWrapper) inEvent.getItemId());
        }
    });
    lTree.addShortcutListener(new ExtendedShortcutListener("enter", KeyCode.ENTER)); //$NON-NLS-1$
}

From source file:org.lucidj.explorer.ExplorerView.java

License:Apache License

private void view_directory(Map<String, Object> entry) {
    String directory = (String) entry.get("directory");
    String caption = (String) entry.get("iconTitle");
    Tree tree = active_trees.get(directory);

    if (tree == null) {
        CustomFilesystemContainer fs = new CustomFilesystemContainer(Paths.get(directory));
        tree = new Tree();
        tree.addStyleName("x-explorerview");
        tree.setContainerDataSource(fs);
        tree.setItemIconPropertyId(FilesystemContainer.PROPERTY_ICON);
        tree.setItemCaptionPropertyId(FilesystemContainer.PROPERTY_NAME);
        tree.setSelectable(false);//from w  ww.  j  a v  a2s.c o  m
        tree.setImmediate(true);
        tree.setHeightUndefined();
        tree.addItemClickListener(this);
        active_trees.put(directory, tree);
    }

    // Refresh the tree and switch over
    tree.setContainerDataSource(tree.getContainerDataSource());
    browse_files.setContent(tree);
    browse_files.setCaption(caption);
}

From source file:org.ripla.web.demo.widgets.views.TreeWidgetsView.java

License:Open Source License

/**
 * @param inCountryContainer//  ww  w  .j a v a  2  s.  c om
 */
public TreeWidgetsView(final CountryTree inCountries) {
    super();

    final IMessages lMessages = Activator.getMessages();
    final VerticalLayout lLayout = initLayout(lMessages, "widgets.title.page.tree"); //$NON-NLS-1$

    final Tree lTree = new Tree(lMessages.getMessage("widgets.view.tree.title")); //$NON-NLS-1$
    lTree.setContainerDataSource(inCountries);
    lTree.setImmediate(true);
    lTree.addItemClickListener(new ItemClickEvent.ItemClickListener() {
        @Override
        public void itemClick(final ItemClickEvent inEvent) {
            final Object lItem = inEvent.getItemId();
            if (lItem instanceof CountryBean) {
                Popup.displayPopup(lMessages.getMessage("widgets.view.tree.popup"), //$NON-NLS-1$
                        createCountryPopup((CountryBean) lItem), 260, 685);
            } else {
                if (lTree.isExpanded(lItem)) {
                    lTree.collapseItem(lItem);
                } else {
                    lTree.expandItem(lItem);
                }
            }
        }
    });

    lLayout.addComponent(lTree);
}