Example usage for com.vaadin.ui ComboBox addValueChangeListener

List of usage examples for com.vaadin.ui ComboBox addValueChangeListener

Introduction

In this page you can find the example usage for com.vaadin.ui ComboBox addValueChangeListener.

Prototype

@Override
    public Registration addValueChangeListener(HasValue.ValueChangeListener<T> listener) 

Source Link

Usage

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

License:Apache License

private Component getConfigurableTab() {
    VerticalLayout vl = new VerticalLayout();
    ComboBox options = new ComboBox();
    options.addItem(ISSUE_TYPE);//from  ww w  .j  av a  2 s . co  m
    options.setItemCaption(ISSUE_TYPE, TRANSLATOR.translate(ISSUE_TYPE));
    options.addItem(ISSUE_RESOLUTION);
    options.setItemCaption(ISSUE_RESOLUTION, TRANSLATOR.translate(ISSUE_RESOLUTION));
    options.addItem(REQUIREMENT_TYPE);
    options.setItemCaption(REQUIREMENT_TYPE, TRANSLATOR.translate(REQUIREMENT_TYPE));
    options.setTextInputAllowed(false);
    options.addValueChangeListener((Property.ValueChangeEvent event) -> {
        Component nextComp = null;
        if (options.getValue() != null) {
            switch ((String) options.getValue()) {
            case ISSUE_TYPE:
                nextComp = displayIssueTypes();
                break;
            case ISSUE_RESOLUTION:
                nextComp = displayIssueResolutions();
                break;
            case REQUIREMENT_TYPE:
                nextComp = displayRequirementTypes();
                break;
            default:
                //Do nothing
            }
        }
        if (nextComp != null) {
            vl.removeAllComponents();
            vl.addComponent(options);
            vl.addComponent(nextComp);
        }
    });
    vl.addComponent(options);
    vl.setSizeFull();
    return vl;
}

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

License:Apache License

private void init() {
    tree = new Tree();
    tree.addItem(getTemplate());//from  w w  w  .j av a  2 s. c  o  m
    tree.setItemIcon(getTemplate(), VaadinIcons.FILE_TREE);
    tree.setItemCaption(getTemplate(), getTemplate().getTemplateName());
    if (getTemplate().getTemplateNodeList() != null) {
        getTemplate().getTemplateNodeList().forEach(node -> {
            if (node.getTemplateNode() == null) {
                //Only root folders
                addTemplateNode(node);
            }
        });
    }
    //Select item on right click as well
    tree.addItemClickListener((ItemClickEvent event) -> {
        if (event.getSource() == tree && event.getButton() == MouseEventDetails.MouseButton.RIGHT) {
            if (event.getItem() != null) {
                Item clicked = event.getItem();
                tree.select(event.getItemId());
            }
        }
    });
    //Add context menu
    ContextMenu menu = new ContextMenu(tree, true);
    if (edit) {
        tree.addItemClickListener((ItemClickEvent event) -> {
            if (event.getButton() == MouseEventDetails.MouseButton.RIGHT) {
                menu.removeItems();
                if (tree.getValue() != null) {
                    if (tree.getValue() instanceof Template) {
                        Template t = (Template) tree.getValue();
                        if (t.getId() < 1_000) {
                            return;
                        }
                    }
                    MenuItem create = menu.addItem(TRANSLATOR.translate("general.add.child"), PROJECT_ICON,
                            (MenuItem selectedItem) -> {
                                displayChildCreationWizard();
                            });
                    MenuItem delete = menu.addItem(TRANSLATOR.translate("general.delete"), PROJECT_ICON,
                            (MenuItem selectedItem) -> {
                                displayChildDeletionWizard();
                            });
                    //Don't allow to delete the root node.
                    delete.setEnabled(!tree.isRoot(tree.getValue()));
                }
            }
        });
    }
    TextField nameField = new TextField(TRANSLATOR.translate("general.name"));
    VerticalLayout vl = new VerticalLayout();
    BeanFieldGroup binder = new BeanFieldGroup(getTemplate().getClass());
    binder.setItemDataSource(getTemplate());
    binder.bind(nameField, "templateName");
    nameField.addValueChangeListener(listener -> {
        getTemplate().setTemplateName(nameField.getValue());
    });
    nameField.setNullRepresentation("");
    ComboBox type = new ComboBox(TRANSLATOR.translate("general.type"));
    BeanItemContainer<ProjectType> container = new BeanItemContainer<>(ProjectType.class,
            new ProjectTypeJpaController(DataBaseManager.getEntityManagerFactory()).findProjectTypeEntities());
    type.setContainerDataSource(container);
    for (Object o : type.getItemIds()) {
        ProjectType id = ((ProjectType) o);
        type.setItemCaption(id, TRANSLATOR.translate(id.getTypeName()));
    }
    type.addValueChangeListener(listener -> {
        if (type.getValue() != null) {
            getTemplate().setProjectTypeId((ProjectType) type.getValue());
        }
    });
    binder.bind(type, "projectTypeId");
    vl.addComponent(nameField);
    vl.addComponent(type);
    if (template.getId() != null) {
        vl.addComponent(tree);
    }
    binder.setReadOnly(!edit);
    setContent(vl);
}

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

License:Apache License

public Component getMenu() {
    HorizontalLayout hl = new HorizontalLayout();
    ComboBox baseline = new ComboBox(TRANSLATOR.translate("baseline.filter"));
    baseline.setTextInputAllowed(false);
    baseline.setNewItemsAllowed(false);//w  w  w. j a v  a2 s  . c o  m
    Tool.extractRequirements(p).forEach(r -> {
        r.getHistoryList().forEach(h -> {
            h.getBaselineList().forEach(b -> {
                if (!baseline.containsId(b)) {
                    baseline.addItem(b);
                    baseline.setItemCaption(b, b.getBaselineName());
                }
            });
        });
    });
    baseline.addValueChangeListener(event -> {
        removeAllItems();
        Baseline b = (Baseline) baseline.getValue();
        if (b == null) {
            //None selected, no filtering
            Tool.extractRequirements(p).forEach((r) -> {
                if (r.getParentRequirementId() == null) {
                    addRequirement(r);
                }
            });
        } else {
            b.getHistoryList().forEach(h -> {
                addRequirement(h.getRequirementId());
            });
        }
    });
    hl.addComponent(baseline);
    Button export = new Button(TRANSLATOR.translate("general.export"));
    export.addClickListener(listener -> {
        //Create the Excel file
        ExcelExport excelExport = new ExcelExport(this);
        excelExport.excludeCollapsedColumns();
        excelExport.setReportTitle(TRANSLATOR.translate("trace.matrix"));
        excelExport.setDisplayTotals(false);
        excelExport.export();
    });
    hl.addComponent(export);
    return hl;
}

From source file:org.apache.openaz.xacml.admin.view.components.RangeEditorComponent.java

License:Apache License

private void setupComboText(final ComboBox box, final TextField text) {
    ///*from  w ww .  j  a  v  a 2  s  . c  o m*/
    // Respond to combo changes
    //
    box.addValueChangeListener(new ValueChangeListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void valueChange(ValueChangeEvent event) {
            //
            // Get the new value
            //
            String property = (String) box.getValue();
            //
            // Get our constraint object
            //
            ConstraintValue value = (ConstraintValue) box.getData();
            //
            // Update our object
            //
            if (property == null) {
                //
                // Clear the text field and disable it
                //
                text.setEnabled(false);
                text.setValue(null);
            } else {
                //
                // Change the property name
                //
                value.setProperty(property);
                //
                // Focus to the text field and enable it
                //
                text.setEnabled(true);
                text.focus();
            }
        }
    });

}

From source file:org.asi.ui.pagedtable.PagedTable.java

License:Apache License

public HorizontalLayout createControls(PagedControlConfig config) {
    Label itemsPerPageLabel = new Label(config.getItemsPerPage(), ContentMode.HTML);
    itemsPerPageLabel.setSizeUndefined();
    final ComboBox itemsPerPageSelect = new ComboBox();

    for (Integer i : config.getPageLengths()) {
        itemsPerPageSelect.addItem(i);/*from  w  w w  .  j av  a2 s .  c om*/
        itemsPerPageSelect.setItemCaption(i, String.valueOf(i));
    }
    itemsPerPageSelect.setImmediate(true);
    itemsPerPageSelect.setNullSelectionAllowed(false);
    itemsPerPageSelect.setWidth(null);
    itemsPerPageSelect.addValueChangeListener(new Property.ValueChangeListener() {
        private static final long serialVersionUID = -2255853716069800092L;

        @Override
        public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
            setPageLength((Integer) event.getProperty().getValue());
        }
    });
    if (itemsPerPageSelect.containsId(getPageLength())) {
        itemsPerPageSelect.select(getPageLength());
    } else {
        itemsPerPageSelect.select(itemsPerPageSelect.getItemIds().iterator().next());
    }
    Label pageLabel = new Label(config.getPage(), ContentMode.HTML);
    final TextField currentPageTextField = new TextField();
    currentPageTextField.setValue(String.valueOf(getCurrentPage()));
    currentPageTextField.setConverter(new StringToIntegerConverter() {
        @Override
        protected NumberFormat getFormat(Locale locale) {
            NumberFormat result = super.getFormat(UI.getCurrent().getLocale());
            result.setGroupingUsed(false);
            return result;
        }
    });
    Label separatorLabel = new Label("&nbsp;/&nbsp;", ContentMode.HTML);
    final Label totalPagesLabel = new Label(String.valueOf(getTotalAmountOfPages()), ContentMode.HTML);
    currentPageTextField.setStyleName(Reindeer.TEXTFIELD_SMALL);
    currentPageTextField.setImmediate(true);
    currentPageTextField.addValueChangeListener(new Property.ValueChangeListener() {
        private static final long serialVersionUID = -2255853716069800092L;

        @Override
        public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
            if (currentPageTextField.isValid() && currentPageTextField.getValue() != null) {
                int page = Integer.valueOf(String.valueOf(currentPageTextField.getValue()));
                setCurrentPage(page);
            }
        }
    });
    pageLabel.setWidth(null);
    currentPageTextField.setColumns(3);
    separatorLabel.setWidth(null);
    totalPagesLabel.setWidth(null);

    HorizontalLayout controlBar = new HorizontalLayout();
    HorizontalLayout pageSize = new HorizontalLayout();
    HorizontalLayout pageManagement = new HorizontalLayout();
    final Button first = new Button(config.getFirst(), new Button.ClickListener() {
        private static final long serialVersionUID = -355520120491283992L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            setCurrentPage(0);
        }
    });
    final Button previous = new Button(config.getPrevious(), new Button.ClickListener() {
        private static final long serialVersionUID = -355520120491283992L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            previousPage();
        }
    });
    final Button next = new Button(config.getNext(), new Button.ClickListener() {
        private static final long serialVersionUID = -1927138212640638452L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            nextPage();
        }
    });
    final Button last = new Button(config.getLast(), new Button.ClickListener() {
        private static final long serialVersionUID = -355520120491283992L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            setCurrentPage(getTotalAmountOfPages());
        }
    });
    first.setStyleName(Reindeer.BUTTON_LINK);
    previous.setStyleName(Reindeer.BUTTON_LINK);
    next.setStyleName(Reindeer.BUTTON_LINK);
    last.setStyleName(Reindeer.BUTTON_LINK);

    itemsPerPageLabel.addStyleName("pagedtable-itemsperpagecaption");
    itemsPerPageSelect.addStyleName("pagedtable-itemsperpagecombobox");
    pageLabel.addStyleName("pagedtable-pagecaption");
    currentPageTextField.addStyleName("pagedtable-pagefield");
    separatorLabel.addStyleName("pagedtable-separator");
    totalPagesLabel.addStyleName("pagedtable-total");
    first.addStyleName("pagedtable-first");
    previous.addStyleName("pagedtable-previous");
    next.addStyleName("pagedtable-next");
    last.addStyleName("pagedtable-last");

    itemsPerPageLabel.addStyleName("pagedtable-label");
    itemsPerPageSelect.addStyleName("pagedtable-combobox");
    pageLabel.addStyleName("pagedtable-label");
    currentPageTextField.addStyleName("pagedtable-label");
    separatorLabel.addStyleName("pagedtable-label");
    totalPagesLabel.addStyleName("pagedtable-label");
    first.addStyleName("pagedtable-button");
    previous.addStyleName("pagedtable-button");
    next.addStyleName("pagedtable-button");
    last.addStyleName("pagedtable-button");

    pageSize.addComponent(itemsPerPageLabel);
    pageSize.addComponent(itemsPerPageSelect);
    pageSize.setComponentAlignment(itemsPerPageLabel, Alignment.MIDDLE_LEFT);
    pageSize.setComponentAlignment(itemsPerPageSelect, Alignment.MIDDLE_LEFT);
    pageSize.setSpacing(true);
    pageManagement.addComponent(first);
    pageManagement.addComponent(previous);
    pageManagement.addComponent(pageLabel);
    pageManagement.addComponent(currentPageTextField);
    pageManagement.addComponent(separatorLabel);
    pageManagement.addComponent(totalPagesLabel);
    pageManagement.addComponent(next);
    pageManagement.addComponent(last);
    pageManagement.setComponentAlignment(first, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(previous, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(pageLabel, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(currentPageTextField, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(separatorLabel, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(totalPagesLabel, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(next, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(last, Alignment.MIDDLE_LEFT);
    pageManagement.setWidth(null);
    pageManagement.setSpacing(true);
    controlBar.addComponent(pageSize);
    controlBar.addComponent(pageManagement);
    controlBar.setComponentAlignment(pageManagement, Alignment.MIDDLE_CENTER);
    controlBar.setWidth(100, Sizeable.Unit.PERCENTAGE);
    controlBar.setExpandRatio(pageSize, 1);

    if (container != null) {
        first.setEnabled(container.getStartIndex() > 0);
        previous.setEnabled(container.getStartIndex() > 0);
        next.setEnabled(container.getStartIndex() < container.getRealSize() - getPageLength());
        last.setEnabled(container.getStartIndex() < container.getRealSize() - getPageLength());
    }

    addListener(new PageChangeListener() {
        private boolean inMiddleOfValueChange;

        @Override
        public void pageChanged(PagedTableChangeEvent event) {
            if (!inMiddleOfValueChange) {
                inMiddleOfValueChange = true;
                first.setEnabled(container.getStartIndex() > 0);
                previous.setEnabled(container.getStartIndex() > 0);
                next.setEnabled(container.getStartIndex() < container.getRealSize() - getPageLength());
                last.setEnabled(container.getStartIndex() < container.getRealSize() - getPageLength());
                currentPageTextField.setValue(String.valueOf(getCurrentPage()));
                totalPagesLabel.setValue(Integer.toString(getTotalAmountOfPages()));
                itemsPerPageSelect.setValue(getPageLength());
                inMiddleOfValueChange = false;
            }
        }
    });
    return controlBar;
}

From source file:org.azrul.langkuik.framework.webgui.BeanView.java

private void createForm(EntityRight entityRight, final Set<String> currentUserRoles,
        final Map<String, Map<Integer, FieldContainer>> groups, String group, final BeanFieldGroup fieldGroup,
        final List<DataAccessObject<?>> customTypeDaos, final Navigator nav, final FormLayout form)
        throws FieldGroup.BindException, UnsupportedOperationException {
    //create bean utils
    final BeanUtils beanUtils = new BeanUtils();

    //select which group we want
    Map<Integer, FieldContainer> fieldContainerMap = null;
    if (group == null) {
        fieldContainerMap = groups.entrySet().iterator().next().getValue();
    } else {//from   w ww . j av a2  s  . co  m
        fieldContainerMap = groups.get(group);
    }

    //collect all activechoices
    Map<com.vaadin.ui.ComboBox, ActiveChoiceTarget> activeChoicesWithFieldAsKey = new HashMap<>();
    Map<String, com.vaadin.ui.ComboBox> activeChoicesFieldWithHierarchyAsKey = new HashMap<>();

    //collect all cutsom types
    List<Class> customTypes = new ArrayList<>();
    for (DataAccessObject<?> ctDao : customTypeDaos) {
        customTypes.add(ctDao.getType());
    }
    //deal with every field
    everyField: for (Map.Entry<Integer, FieldContainer> entry : fieldContainerMap.entrySet()) {
        final FieldContainer fieldContainer = entry.getValue();
        final ComponentState effectiveFieldState = beanUtils
                .calculateEffectiveComponentState(fieldContainer.getPojoField(), currentUserRoles, entityRight);

        //Create form
        if (ComponentState.INVISIBLE.equals(effectiveFieldState)) {
            continue everyField; //Continue with next field
        }

        //deal with normal form element
        com.vaadin.ui.Field uifield = null;
        //deal with plain choices
        if (fieldContainer.getWebField().choices().length > 0) {
            //deal with choices
            com.vaadin.ui.ComboBox formComboBox = new com.vaadin.ui.ComboBox(
                    fieldContainer.getWebField().name());
            formComboBox.setImmediate(true);
            fieldGroup.bind(formComboBox, fieldContainer.getPojoField().getName());
            for (Choice choice : fieldContainer.getWebField().choices()) {
                if (choice.value() == -1) {
                    formComboBox.addItem(choice.textValue());
                    formComboBox.setItemCaption(choice.textValue(), choice.display());
                } else {
                    formComboBox.addItem(choice.value());
                    formComboBox.setItemCaption(choice.value(), choice.display());
                }
            }
            form.addComponent(formComboBox);
            uifield = formComboBox;
            //deal with active choices
        } else if (fieldContainer.getWebField().activeChoice().enumTree() != EmptyEnum.class) {
            //collect active choices - 
            com.vaadin.ui.ComboBox formComboBox = new com.vaadin.ui.ComboBox(
                    fieldContainer.getWebField().name());
            formComboBox.setImmediate(true);
            fieldGroup.bind(formComboBox, fieldContainer.getPojoField().getName());
            String hierarchy = fieldContainer.getWebField().activeChoice().hierarchy();
            Class<ActiveChoiceEnum> enumTree = (Class<ActiveChoiceEnum>) fieldContainer.getWebField()
                    .activeChoice().enumTree();
            ActiveChoiceTarget activeChoiceTarget = ActiveChoiceUtils.build(enumTree, hierarchy);
            for (String choice : activeChoiceTarget.getSourceChoices()) {
                formComboBox.addItem(choice);
                activeChoicesWithFieldAsKey.put(formComboBox, activeChoiceTarget);
                activeChoicesFieldWithHierarchyAsKey.put(hierarchy, formComboBox);
            }

            form.addComponent(formComboBox);
            uifield = formComboBox;

            //deal with relationship
        } else if (fieldContainer.getPojoField().isAnnotationPresent(OneToMany.class)
                || fieldContainer.getPojoField().isAnnotationPresent(ManyToOne.class)
                || fieldContainer.getPojoField().isAnnotationPresent(ManyToMany.class)) {

            //special relationship: deal with custom type form element
            int state = 0;
            Class classOfField = null;
            while (true) {
                if (state == 0) {
                    if (Collection.class.isAssignableFrom(fieldContainer.getPojoField().getType())) {
                        classOfField = (Class) ((ParameterizedType) fieldContainer.getPojoField()
                                .getGenericType()).getActualTypeArguments()[0];
                        state = 1;
                    } else {
                        state = 3;
                        break;
                    }
                }
                if (state == 1) {
                    if (CustomType.class.isAssignableFrom(classOfField)) {
                        state = 2;
                        break;
                    } else {
                        state = 3;
                        break;
                    }
                }
            }

            if (state == 2) { //Custom type
                Button openCustom = new Button("Manage " + fieldContainer.getWebField().name(),
                        new Button.ClickListener() {
                            @Override
                            public void buttonClick(ClickEvent event) {
                                try {
                                    fieldGroup.commit();
                                    currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                    currentBean = saveBean(currentBean, parentBean, beanUtils,
                                            currentUserRoles);
                                    fieldGroup.setItemDataSource(currentBean);
                                    //field class
                                    Class iclassOfField = (Class) ((ParameterizedType) fieldContainer
                                            .getPojoField().getGenericType()).getActualTypeArguments()[0];

                                    //find a custom type dao
                                    DataAccessObject<? extends CustomType> chosenCTDao = null;
                                    for (DataAccessObject cdao : customTypeDaos) {
                                        if (cdao.getType().isAssignableFrom(iclassOfField)) {
                                            chosenCTDao = cdao;
                                            break;
                                        }
                                    }

                                    //deal with windows
                                    final Window window = new Window();
                                    final AttachmentCustomTypeUICreator<C> attachmentCustomTypeUICreator = new AttachmentCustomTypeUICreator();
                                    Component customTypeComponent = attachmentCustomTypeUICreator
                                            .createUIForForm(currentBean, iclassOfField,
                                                    fieldContainer.getPojoField().getName(), BeanView.this, dao,
                                                    chosenCTDao, pageParameter.getRelationManagerFactory(),
                                                    pageParameter.getConfig(), effectiveFieldState, window);
                                    customTypeComponent
                                            .setCaption("Manage " + fieldContainer.getWebField().name());
                                    customTypeComponent.setId(customTypeComponent.getCaption());
                                    window.setCaption(customTypeComponent.getCaption());
                                    window.setId(window.getCaption());
                                    window.setContent(customTypeComponent);
                                    window.setModal(true);

                                    BeanView.this.getUI().addWindow(window);
                                } catch (CommitException ex) {
                                    handleFieldsError(fieldGroup);
                                }
                            }
                        });
                openCustom.setId(openCustom.getCaption());
                form.addComponent(openCustom);

            } else { //relationship
                try {
                    fieldContainer.getPojoField().setAccessible(true);
                    final WebField webField = fieldContainer.getPojoField().getAnnotation(WebField.class);
                    Button relationshipButton = null;
                    if (fieldContainer.getPojoField().isAnnotationPresent(OneToMany.class)) {
                        relationshipButton = new Button("Manage " + webField.name(),
                                new Button.ClickListener() {
                                    @Override
                                    public void buttonClick(Button.ClickEvent event) {
                                        try {
                                            fieldGroup.commit();
                                            currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                            currentBean = saveBean(currentBean, parentBean, beanUtils,
                                                    currentUserRoles);

                                            Class classOfField = (Class) ((ParameterizedType) fieldContainer
                                                    .getPojoField().getGenericType())
                                                            .getActualTypeArguments()[0];
                                            EditorTableView view = new EditorTableView(currentBean,
                                                    fieldContainer.getPojoField().getName(),
                                                    effectiveFieldState, classOfField, ChoiceType.CHOOSE_MANY,
                                                    pageParameter);
                                            String targetView = "BEAN_VIEW_" + UUID.randomUUID().toString();
                                            History his = new History(targetView, "Manage " + webField.name());
                                            pageParameter.getHistory().push(his);
                                            nav.addView(targetView, view);
                                            nav.navigateTo(targetView);
                                        } catch (CommitException ex) {
                                            handleFieldsError(fieldGroup);
                                        }
                                    }
                                });

                    } else if (fieldContainer.getPojoField().isAnnotationPresent(ManyToOne.class)) {
                        relationshipButton = new Button("Manage " + webField.name(),
                                new Button.ClickListener() {
                                    @Override
                                    public void buttonClick(Button.ClickEvent event) {
                                        try {
                                            fieldGroup.commit();
                                            currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                            fieldGroup.commit();
                                            currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                            currentBean = saveBean(currentBean, parentBean, beanUtils,
                                                    currentUserRoles);

                                            EditorTableView view = new EditorTableView(currentBean,
                                                    fieldContainer.getPojoField().getName(),
                                                    effectiveFieldState,
                                                    fieldContainer.getPojoField().getType(),
                                                    ChoiceType.CHOOSE_ONE, pageParameter);
                                            String targetView = "BEAN_VIEW_" + UUID.randomUUID().toString();
                                            History his = new History(targetView, "Manage " + webField.name());
                                            pageParameter.getHistory().push(his);
                                            nav.addView(targetView, view);
                                            nav.navigateTo(targetView);
                                        } catch (CommitException ex) {
                                            handleFieldsError(fieldGroup);
                                        }
                                    }
                                });
                    } else if (fieldContainer.getPojoField().isAnnotationPresent(ManyToMany.class)) {
                        relationshipButton = new Button("Manage " + webField.name(),
                                new Button.ClickListener() {
                                    @Override
                                    public void buttonClick(Button.ClickEvent event) {
                                        try {
                                            fieldGroup.commit();
                                            currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                            fieldGroup.commit();
                                            currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                            currentBean = saveBean(currentBean, parentBean, beanUtils,
                                                    currentUserRoles);

                                            Class classOfField = (Class) ((ParameterizedType) fieldContainer
                                                    .getPojoField().getGenericType())
                                                            .getActualTypeArguments()[0];
                                            EditorTableView view = new EditorTableView(currentBean,
                                                    fieldContainer.getPojoField().getName(),
                                                    effectiveFieldState, classOfField, ChoiceType.CHOOSE_MANY,
                                                    pageParameter);

                                            String targetView = "BEAN_VIEW_" + UUID.randomUUID().toString();
                                            History his = new History(targetView, "Manage " + webField.name());
                                            pageParameter.getHistory().push(his);
                                            nav.addView(targetView, view);
                                            nav.navigateTo(targetView);
                                        } catch (CommitException ex) {
                                            handleFieldsError(fieldGroup);
                                        }
                                    }
                                });
                    }
                    relationshipButton.setId(relationshipButton.getCaption());
                    form.addComponent(relationshipButton);
                } catch (IllegalArgumentException ex) {
                    Logger.getLogger(BeanView.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            //deal with id
        } else if (fieldContainer.getPojoField().isAnnotationPresent(Id.class)) {
            com.vaadin.ui.Field formField = fieldGroup.buildAndBind(fieldContainer.getWebField().name(),
                    fieldContainer.getPojoField().getName());
            if (Number.class.isAssignableFrom(fieldContainer.getPojoField().getType())) {
                ((TextField) formField).setConverter(
                        new NumberBasedIDConverter((Class<Number>) fieldContainer.getPojoField().getType()));
            }

            form.addComponent(formField);
            uifield = formField;

            //deal with nominal form element
        } else {
            com.vaadin.ui.Field formField = fieldGroup.buildAndBind(fieldContainer.getWebField().name(),
                    fieldContainer.getPojoField().getName());
            if (fieldContainer.getPojoField().getType().equals(Date.class)) {
                //deal with date
                DateField dateField = (DateField) formField;
                dateField.setDateFormat(pageParameter.getConfig().get("dateFormat"));
                dateField.setWidth(100f, Unit.PIXELS);
            } else if (fieldContainer.getPojoField().getType().equals(BigDecimal.class)) {
                TextField bdField = (TextField) formField;
                bdField.setConverter(new StringToBigDecimalConverter());
            }

            form.addComponent(formField);
            uifield = formField;
        }

        if (uifield != null) {
            //deal with read only
            if (ComponentState.READ_ONLY.equals(effectiveFieldState)) {
                uifield.setReadOnly(true);
            } else {
                uifield.setReadOnly(false);
                if (fieldContainer.getWebField().required() == true) {
                    uifield.setRequired(true);
                }
            }

            //set null presentation
            if (uifield instanceof AbstractTextField) {
                AbstractTextField textField = (AbstractTextField) uifield;
                textField.setNullRepresentation("");
            }

            //set debug id
            uifield.setId(uifield.getCaption());
        }
    }

    //deal with active choice
    for (final com.vaadin.ui.ComboBox sourceField : activeChoicesWithFieldAsKey.keySet()) {
        final ActiveChoiceTarget target = activeChoicesWithFieldAsKey.get(sourceField);
        final com.vaadin.ui.ComboBox targetField = activeChoicesFieldWithHierarchyAsKey
                .get(target.getTargetHierarchy());
        sourceField.addValueChangeListener(new ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                List<String> targetValues = target.getTargets().get(sourceField.getValue());
                if (targetValues != null && !targetValues.isEmpty() && targetField != null) {
                    targetField.removeAllItems();
                    for (String targetValue : targetValues) {
                        targetField.addItem(targetValue);
                    }
                }
            }
        });

    }
}

From source file:org.azrul.langkuik.framework.webgui.SearchDataTableLayout.java

protected void createSearchPanel(final Class<C> classOfBean, final Configuration config,
        final Set<String> currentUserRoles, final EntityRight entityRight)
        throws UnsupportedOperationException, SecurityException, FieldGroup.BindException {
    final BeanFieldGroup fieldGroup = new BeanFieldGroup(classOfBean);
    final FindAnyEntityParameter searchQuery = (FindAnyEntityParameter) parameter;

    //collect all activechoices
    Map<com.vaadin.ui.ComboBox, ActiveChoiceTarget> activeChoicesWithFieldAsKey = new HashMap<>();
    Map<String, com.vaadin.ui.ComboBox> activeChoicesFieldWithHierarchyAsKey = new HashMap<>();

    BeanUtils beanUtils = new BeanUtils();
    Map<Integer, FieldContainer> fieldContainers = beanUtils.getOrderedFieldsByRank(classOfBean);

    final Map<Integer, com.vaadin.ui.Field> searchableFieldsByRank = new TreeMap<>();
    final Map<String, com.vaadin.ui.Field> searchableFieldsByName = new TreeMap<>();

    //Construct search form
    for (FieldContainer fieldContainer : fieldContainers.values()) {
        Field pojoField = fieldContainer.getPojoField();
        WebField webField = fieldContainer.getWebField();

        if (pojoField.isAnnotationPresent(org.hibernate.search.annotations.Field.class)) {
            if (webField.choices().length > 0) {
                //deal with choices

                com.vaadin.ui.ComboBox searchComboBox = new com.vaadin.ui.ComboBox(webField.name());

                searchComboBox.setImmediate(true);
                fieldGroup.bind(searchComboBox, pojoField.getName());
                for (Choice choice : webField.choices()) {
                    if (choice.value() == -1) {
                        searchComboBox.addItem(choice.textValue());
                        searchComboBox.setItemCaption(choice.textValue(), choice.display());
                    } else {
                        searchComboBox.addItem(choice.value());
                        searchComboBox.setItemCaption(choice.value(), choice.display());
                    }//  w  ww.j  a  v a2 s .co  m
                }

                //allDataSearchForm.addComponent(searchComboBox);
                searchableFieldsByRank.put(webField.rank(), searchComboBox);
                searchableFieldsByName.put(pojoField.getName(), searchComboBox);
            } else if (webField.activeChoice().enumTree() != EmptyEnum.class) {
                //collect active choices - 
                com.vaadin.ui.ComboBox searchComboBox = new com.vaadin.ui.ComboBox(webField.name());
                searchComboBox.setImmediate(true);
                fieldGroup.bind(searchComboBox, pojoField.getName());
                String hierarchy = webField.activeChoice().hierarchy();
                Class<ActiveChoiceEnum> enumTree = (Class<ActiveChoiceEnum>) webField.activeChoice().enumTree();
                ActiveChoiceTarget activeChoiceTarget = ActiveChoiceUtils.build(enumTree, hierarchy);
                for (String choice : activeChoiceTarget.getSourceChoices()) {
                    searchComboBox.addItem(choice);
                    activeChoicesWithFieldAsKey.put(searchComboBox, activeChoiceTarget);
                    activeChoicesFieldWithHierarchyAsKey.put(hierarchy, searchComboBox);
                }
                searchableFieldsByRank.put(webField.rank(), searchComboBox);
                searchableFieldsByName.put(pojoField.getName(), searchComboBox);

            } else {
                com.vaadin.ui.Field searchField = fieldGroup.buildAndBind(webField.name(), pojoField.getName());
                if (pojoField.getType().equals(Date.class)) {
                    DateField dateField = (DateField) searchField;
                    dateField.setDateFormat(config.get("dateFormat"));
                    dateField.setWidth(100f, Sizeable.Unit.PIXELS);
                }

                //allDataSearchForm.addComponent(searchField);
                searchableFieldsByRank.put(webField.rank(), searchField);
                searchableFieldsByName.put(pojoField.getName(), searchField);
            }
        }

    }

    //build form
    int rowCount = (int) (Math.ceil(searchableFieldsByRank.size() / 2));
    rowCount = rowCount < 1 ? 1 : rowCount;
    GridLayout allDataSearchForm = new GridLayout(2, rowCount);
    allDataSearchForm.setSpacing(true);
    for (com.vaadin.ui.Field searchField : searchableFieldsByRank.values()) {
        allDataSearchForm.addComponent(searchField);
        searchField.setId(searchField.getCaption());
    }

    this.addComponent(allDataSearchForm);

    //deal with active choice
    for (final com.vaadin.ui.ComboBox sourceField : activeChoicesWithFieldAsKey.keySet()) {
        final ActiveChoiceTarget target = activeChoicesWithFieldAsKey.get(sourceField);
        final com.vaadin.ui.ComboBox targetField = activeChoicesFieldWithHierarchyAsKey
                .get(target.getTargetHierarchy());
        sourceField.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                List<String> targetValues = target.getTargets().get(sourceField.getValue());
                if (targetValues != null && !targetValues.isEmpty() && targetField != null) {
                    targetField.removeAllItems();
                    for (String targetValue : targetValues) {
                        targetField.addItem(targetValue);
                    }
                }
            }
        });

    }

    //search button
    Button searchBtn = new Button("Search", new Button.ClickListener() {

        @Override
        public void buttonClick(Button.ClickEvent event) {

            //reset previous searches
            searchQuery.getSearchTerms().clear();
            //read search terms from form
            try {
                for (Map.Entry<String, com.vaadin.ui.Field> entry : searchableFieldsByName.entrySet()) {
                    com.vaadin.ui.Field searchField = entry.getValue();
                    if (searchField.getValue() != null) {
                        if (searchField.getValue() instanceof String) {
                            String searchTerm = ((String) searchField.getValue()).trim();
                            if (!"".equals(searchTerm)) {
                                searchQuery.getSearchTerms().add(new SearchTerm(entry.getKey(),
                                        classOfBean.getDeclaredField(entry.getKey()), searchField.getValue()));
                            }
                        } else {
                            searchQuery.getSearchTerms().add(new SearchTerm(entry.getKey(),
                                    classOfBean.getDeclaredField(entry.getKey()), searchField.getValue()));
                        }
                    }
                }
            } catch (NoSuchFieldException | SecurityException ex) {
                Logger.getLogger(SearchDataTableLayout.class.getName()).log(Level.SEVERE, null, ex);
            }
            //do query
            Collection<C> allData = dao.runQuery(parameter, orderBy, asc, currentTableIndex, itemCountPerPage);
            if (allData.isEmpty()) {
                allData = new ArrayList<>();
                allData.add(dao.createNew());
            }
            bigTotal = dao.countQueryResult(parameter);
            itemContainer.setBeans(allData);
            itemContainer.refreshItems();
            table.setPageLength(itemCountPerPage);
            table.setPageLength(itemCountPerPage);
            currentTableIndex = 0;
            int lastPage = (int) Math.floor(bigTotal / itemCountPerPage);
            if (bigTotal % itemCountPerPage == 0) {
                lastPage--;
            }
            int currentUpdatedPage = currentTableIndex / itemCountPerPage;
            pageLabel.setCaption(" " + (currentUpdatedPage + 1) + " of " + (lastPage + 1) + " ");
        }
    });
    searchBtn.setId(searchBtn.getCaption());
    this.addComponent(searchBtn);
}

From source file:org.eclipse.hawkbit.ui.common.builder.ComboBoxBuilder.java

License:Open Source License

/**
 * @return a new ComboBox//from  ww w  . ja  v a2s.c  o m
 */
public ComboBox buildCombBox() {
    final ComboBox comboBox = SPUIComponentProvider.getComboBox(null, "", null, ValoTheme.COMBOBOX_SMALL, false,
            "", prompt);
    comboBox.setImmediate(true);
    comboBox.setPageLength(7);
    comboBox.setItemCaptionPropertyId(SPUILabelDefinitions.VAR_NAME);
    comboBox.setSizeUndefined();
    if (caption != null) {
        comboBox.setCaption(caption);
    }
    if (id != null) {
        comboBox.setId(id);
    }
    if (valueChangeListener != null) {
        comboBox.addValueChangeListener(valueChangeListener);
    }
    return comboBox;
}

From source file:org.hip.vif.web.util.ConfigurableSelect.java

License:Open Source License

/**
 * Create the <code>ComboBox</code> widget containing the registered member
 * authenticators/searchers./*w  ww . j ava2 s .co m*/
 * 
 * @param inItems
 *            String[] the bundle names of registered
 *            authenticators/searchers
 * @param inProperty
 *            {@link Property} the selected item
 * @param inWidth
 *            int the widget width
 * @return {@link ComboBox}
 */
@SuppressWarnings("serial")
public static ComboBox getSelect(final String[] inItems, final Property<String> inProperty, final int inWidth) {
    final ComboBox outSelect = createSelect(inItems);
    outSelect.select(inProperty.getValue().toString());
    outSelect.setStyleName("vif-select"); //$NON-NLS-1$
    outSelect.setWidth(inWidth, Unit.PIXELS);
    outSelect.setNullSelectionAllowed(false);
    outSelect.setImmediate(true);
    outSelect.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(final ValueChangeEvent inEvent) {
            final String lValue = (String) inEvent.getProperty().getValue();
            inProperty.setValue(lValue);
        }
    });

    return outSelect;
}

From source file:org.hip.vif.web.util.DBDriverSelect.java

License:Open Source License

/** Create the <code>Select</code> widget containing the registered DB drivers.
 *
 * @param inProperty {@link Property}/*ww w . j  a  va 2 s.c om*/
 * @param inWidth int
 * @param inAllowNull boolean
 * @param inProcessor {@link IProcessor} may be <code>null</code>
 * @return {@link ComboBox} */
@SuppressWarnings("serial")
public static ComboBox getDBDriverSelection(final Property<String> inProperty, final int inWidth,
        final boolean inAllowNull, final IProcessor inProcessor) {
    final DBDriverContainer lContainer = DBDriverContainer
            .getDBDriverSelection(inProperty.getValue().toString());
    final ComboBox outSelect = new ComboBox(null, lContainer);
    outSelect.select(lContainer.getActiveDriver());
    outSelect.setStyleName("vif-select"); //$NON-NLS-1$
    outSelect.setWidth(inWidth, Unit.PIXELS);
    outSelect.setNullSelectionAllowed(inAllowNull);
    outSelect.setImmediate(true);
    outSelect.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(final ValueChangeEvent inEvent) {
            final String lItemID = ((DBDriverBean) inEvent.getProperty().getValue()).getID();
            inProperty.setValue(lItemID);
            if (inProcessor != null) {
                inProcessor.process(lItemID);
            }
        }
    });
    return outSelect;
}