Example usage for com.vaadin.ui GridLayout GridLayout

List of usage examples for com.vaadin.ui GridLayout GridLayout

Introduction

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

Prototype

public GridLayout(int columns, int rows) 

Source Link

Document

Constructor for a grid of given size (number of columns and rows).

Usage

From source file:org.apache.ace.webui.vaadin.component.ConfirmationDialog.java

License:Apache License

/**
 * Adds all components to this dialog./*from   ww w .j  a  v a 2  s. c o m*/
 * 
 * @param message
 *            the optional message to display, can be <code>null</code>;
 * @param buttonNames
 *            the names of the buttons to add, never <code>null</code> or empty.
 */
protected void addComponents(String message, String defaultButton, String... buttonNames) {
    if (message != null) {
        addComponent(new Label(message));
    }

    GridLayout gl = new GridLayout(buttonNames.length + 1, 1);
    gl.setSpacing(true);
    gl.setWidth("100%");

    gl.addComponent(new Label(" "));
    gl.setColumnExpandRatio(0, 1.0f);

    for (String buttonName : buttonNames) {
        Button button = new Button(buttonName, this);
        button.setData(buttonName);
        if (defaultButton != null && defaultButton.equals(buttonName)) {
            button.setStyleName(Reindeer.BUTTON_DEFAULT);
            button.setClickShortcut(KeyCode.ENTER);
            // Request focus in this window...
            button.focus();
        }
        gl.addComponent(button);
    }

    addComponent(gl);
}

From source file:org.apache.ace.webui.vaadin.VaadinClient.java

License:Apache License

private void initGrid() {
    User user = (User) getUser();//from  w w w .j a va  2s.co  m
    Authorization auth = m_userAdmin.getAuthorization(user);
    int count = 0;
    for (String role : new String[] { "viewArtifact", "viewFeature", "viewDistribution", "viewTarget" }) {
        if (auth.hasRole(role)) {
            count++;
        }
    }

    final GenericUploadHandler uploadHandler = new GenericUploadHandler(m_sessionDir) {
        @Override
        public void updateProgress(long readBytes, long contentLength) {
            Float percentage = new Float(readBytes / (float) contentLength);
            m_progress.setValue(percentage);
        }

        @Override
        protected void artifactsUploaded(List<UploadHandle> uploadedArtifacts) {
            StringBuilder failedMsg = new StringBuilder();
            StringBuilder successMsg = new StringBuilder();
            Set<String> selection = new HashSet<>();

            for (UploadHandle handle : uploadedArtifacts) {
                if (!handle.isSuccessful()) {
                    // Upload failed, so let's report this one...
                    appendFailure(failedMsg, handle);

                    m_log.log(LogService.LOG_ERROR, "Upload of " + handle.getFile() + " failed.",
                            handle.getFailureReason());
                } else {
                    try {
                        // Upload was successful, try to upload it to our OBR...
                        ArtifactObject artifact = uploadToOBR(handle);
                        if (artifact != null) {
                            selection.add(artifact.getDefinition());

                            appendSuccess(successMsg, handle);
                        }
                    } catch (ArtifactAlreadyExistsException exception) {
                        appendFailureExists(failedMsg, handle);

                        m_log.log(LogService.LOG_WARNING,
                                "Upload of " + handle.getFilename() + " failed, as it already exists!");
                    } catch (Exception exception) {
                        appendFailure(failedMsg, handle, exception);

                        m_log.log(LogService.LOG_ERROR, "Upload of " + handle.getFilename() + " failed.",
                                exception);
                    }
                }

                // We're done with this (temporary) file, so we can remove it...
                handle.cleanup();
            }

            m_artifactsPanel.setValue(selection);

            // Notify the user what the overall status was...
            Notification notification = createNotification(failedMsg, successMsg);
            getMainWindow().showNotification(notification);

            m_progress.setStyleName("invisible");
            m_statusLine.setStatus(notification.getCaption() + "...");
        }

        @Override
        protected void uploadStarted(UploadHandle upload) {
            m_progress.setStyleName("visible");
            m_progress.setValue(new Float(0.0f));

            m_statusLine.setStatus("Upload of '%s' started...", upload.getFilename());
        }

        private void appendFailure(StringBuilder sb, UploadHandle handle) {
            appendFailure(sb, handle, handle.getFailureReason());
        }

        private void appendFailure(StringBuilder sb, UploadHandle handle, Exception cause) {
            sb.append("<li>'").append(handle.getFile().getName()).append("': failed");
            if (cause != null) {
                sb.append(", possible reason:<br/>").append(cause.getMessage());
            }
            sb.append("</li>");
        }

        private void appendFailureExists(StringBuilder sb, UploadHandle handle) {
            sb.append("<li>'").append(handle.getFile().getName())
                    .append("': already exists in repository</li>");
        }

        private void appendSuccess(StringBuilder sb, UploadHandle handle) {
            sb.append("<li>'").append(handle.getFile().getName()).append("': added to repository</li>");
        }

        private Notification createNotification(StringBuilder failedMsg, StringBuilder successMsg) {
            String caption = "Upload completed";
            int delay = 500; // msec.
            StringBuilder notification = new StringBuilder();
            if (failedMsg.length() > 0) {
                caption = "Upload completed with failures";
                delay = -1;
                notification.append("<ul>").append(failedMsg).append("</ul>");
            }
            if (successMsg.length() > 0) {
                notification.append("<ul>").append(successMsg).append("</ul>");
            }
            if (delay < 0) {
                notification.append("<p>(click to dismiss this notification).</p>");
            }

            Notification summary = new Notification(caption, notification.toString(),
                    Notification.TYPE_TRAY_NOTIFICATION);
            summary.setDelayMsec(delay);
            return summary;
        }

        private ArtifactObject uploadToOBR(UploadHandle handle) throws IOException {
            return UploadHelper.importRemoteBundle(m_artifactRepository, handle.getFile());
        }
    };

    m_grid = new GridLayout(count, 4);
    m_grid.setSpacing(true);
    m_grid.setSizeFull();

    m_mainToolbar = createToolbar();
    m_grid.addComponent(m_mainToolbar, 0, 0, count - 1, 0);

    m_artifactsPanel = createArtifactsPanel();
    m_artifactToolbar = createArtifactToolbar();

    final DragAndDropWrapper artifactsPanelWrapper = new DragAndDropWrapper(m_artifactsPanel);
    artifactsPanelWrapper.setDragStartMode(DragStartMode.HTML5);
    artifactsPanelWrapper.setDropHandler(new ArtifactDropHandler(uploadHandler));
    artifactsPanelWrapper.setCaption(m_artifactsPanel.getCaption());
    artifactsPanelWrapper.setSizeFull();

    count = 0;
    if (auth.hasRole("viewArtifact")) {
        m_grid.addComponent(artifactsPanelWrapper, count, 2);
        m_grid.addComponent(m_artifactToolbar, count, 1);
        count++;
    }

    m_featuresPanel = createFeaturesPanel();
    m_featureToolbar = createFeatureToolbar();

    if (auth.hasRole("viewFeature")) {
        m_grid.addComponent(m_featuresPanel, count, 2);
        m_grid.addComponent(m_featureToolbar, count, 1);
        count++;
    }

    m_distributionsPanel = createDistributionsPanel();
    m_distributionToolbar = createDistributionToolbar();

    if (auth.hasRole("viewDistribution")) {
        m_grid.addComponent(m_distributionsPanel, count, 2);
        m_grid.addComponent(m_distributionToolbar, count, 1);
        count++;
    }

    m_targetsPanel = createTargetsPanel();
    m_targetToolbar = createTargetToolbar();

    if (auth.hasRole("viewTarget")) {
        m_grid.addComponent(m_targetsPanel, count, 2);
        m_grid.addComponent(m_targetToolbar, count, 1);
    }

    m_statusLine = new StatusLine();

    m_grid.addComponent(m_statusLine, 0, 3, 2, 3);

    m_progress = new ProgressIndicator(0f);
    m_progress.setStyleName("invisible");
    m_progress.setIndeterminate(false);
    m_progress.setPollingInterval(1000);

    m_grid.addComponent(m_progress, 3, 3);

    m_grid.setRowExpandRatio(2, 1.0f);

    m_grid.setColumnExpandRatio(0, 0.31f);
    m_grid.setColumnExpandRatio(1, 0.23f);
    m_grid.setColumnExpandRatio(2, 0.23f);
    m_grid.setColumnExpandRatio(3, 0.23f);

    // Wire up all panels so they have the correct associations...
    m_artifactsPanel.setAssociatedTables(null, m_featuresPanel);
    m_featuresPanel.setAssociatedTables(m_artifactsPanel, m_distributionsPanel);
    m_distributionsPanel.setAssociatedTables(m_featuresPanel, m_targetsPanel);
    m_targetsPanel.setAssociatedTables(m_distributionsPanel, null);

    addListener(m_statusLine, StatefulTargetObject.TOPIC_ALL,
            RepositoryObject.PUBLIC_TOPIC_ROOT.concat(RepositoryObject.TOPIC_ALL_SUFFIX));
    addListener(m_mainToolbar, StatefulTargetObject.TOPIC_ALL, RepositoryAdmin.TOPIC_STATUSCHANGED,
            RepositoryAdmin.TOPIC_LOGIN, RepositoryAdmin.TOPIC_REFRESH);
    addListener(m_artifactsPanel, ArtifactObject.TOPIC_ALL, RepositoryAdmin.TOPIC_STATUSCHANGED,
            RepositoryAdmin.TOPIC_LOGIN, RepositoryAdmin.TOPIC_REFRESH);
    addListener(m_featuresPanel, FeatureObject.TOPIC_ALL, RepositoryAdmin.TOPIC_STATUSCHANGED,
            RepositoryAdmin.TOPIC_LOGIN, RepositoryAdmin.TOPIC_REFRESH);
    addListener(m_distributionsPanel, DistributionObject.TOPIC_ALL, RepositoryAdmin.TOPIC_STATUSCHANGED,
            RepositoryAdmin.TOPIC_LOGIN, RepositoryAdmin.TOPIC_REFRESH);
    addListener(m_targetsPanel, StatefulTargetObject.TOPIC_ALL, TargetObject.TOPIC_ALL,
            RepositoryAdmin.TOPIC_STATUSCHANGED, RepositoryAdmin.TOPIC_LOGIN, RepositoryAdmin.TOPIC_REFRESH);

    m_mainWindow.addComponent(m_grid);
    // Ensure the focus is properly defined (for the shortcut keys to work)...
    m_mainWindow.focus();
}

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());
                    }//from www.  j  av a  2s.  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.balisunrise.vaadin.components.user.UserPanel.java

License:Open Source License

private void init() {

    model = new CreateUserModel();
    BeanItem<CreateUserModel> item = new BeanItem<>(model);
    FieldGroup fg = new FieldGroup(item);

    nome = new TextField("Nome");
    nome.setWidth("100%");
    nome.setMaxLength(50);/*from  w  ww.  ja  v  a2 s . co m*/
    fg.bind(nome, "nome");

    login = new TextField("Login");
    login.setWidth("100%");
    login.setMaxLength(32);
    fg.bind(login, "login");

    senha = new PasswordField("Senha");
    senha.setWidth("100%");
    senha.setMaxLength(32);
    fg.bind(senha, "senha");

    repita = new PasswordField("Repita a senha");
    repita.setWidth("100%");
    repita.setMaxLength(32);
    fg.bind(repita, "repita");

    GridLayout grid = new GridLayout(20, 1);
    grid.setWidth("100%");
    grid.setHeightUndefined();
    grid.setSpacing(true);

    grid.addComponent(nome, 0, 0, 9, 0);
    grid.addComponent(login, 10, 0, 19, 0);
    grid.setRows(2);
    grid.addComponent(senha, 0, 1, 9, 1);
    grid.addComponent(repita, 10, 1, 19, 1);

    addComponent(grid);
    setSpacing(true);

    repita.addBlurListener((e) -> {
        try {
            fg.commit();
            Notification.show("Changes committed!\n" + model.toString(), Notification.Type.TRAY_NOTIFICATION);
        } catch (final FieldGroup.CommitException ex) {
            Notification.show("Commit failed: " + ex.getCause().getMessage(),
                    Notification.Type.TRAY_NOTIFICATION);
        }
    });
}

From source file:org.bubblecloud.ilves.comment.CommentListComponent.java

License:Open Source License

public void refresh() {

    final String contextPath = VaadinService.getCurrentRequest().getContextPath();
    final Site site = Site.getCurrent();

    final Company company = site.getSiteContext().getObject(Company.class);
    final EntityManager entityManager = site.getSiteContext().getObject(EntityManager.class);

    final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    final CriteriaQuery<Comment> commentCriteriaQuery = builder.createQuery(Comment.class);
    final Root<Comment> commentRoot = commentCriteriaQuery.from(Comment.class);
    commentCriteriaQuery.where(builder.and(builder.equal(commentRoot.get("owner"), company),
            builder.equal(commentRoot.get("dataId"), contextPath)));
    commentCriteriaQuery.orderBy(builder.asc(commentRoot.get("created")));

    final TypedQuery<Comment> commentTypedQuery = entityManager.createQuery(commentCriteriaQuery);
    final List<Comment> commentList = commentTypedQuery.getResultList();

    final Panel panel = new Panel(site.localize("panel-comments"));
    setCompositionRoot(panel);//  ww w . ja  v a  2 s .c o  m

    final GridLayout gridLayout = new GridLayout(3, commentList.size() + 1);
    panel.setContent(gridLayout);
    gridLayout.setSpacing(true);
    gridLayout.setMargin(true);
    gridLayout.setColumnExpandRatio(0, 0.0f);
    gridLayout.setColumnExpandRatio(1, 0.1f);
    gridLayout.setColumnExpandRatio(2, 0.9f);

    final Label authorHeaderLabel = new Label();
    authorHeaderLabel.setStyleName(ValoTheme.LABEL_BOLD);
    authorHeaderLabel.setValue(site.localize("column-header-author"));
    gridLayout.addComponent(authorHeaderLabel, 0, 0, 1, 0);

    final Label commentHeaderLabel = new Label();
    commentHeaderLabel.setStyleName(ValoTheme.LABEL_BOLD);
    commentHeaderLabel.setValue(site.localize("column-header-comment"));
    gridLayout.addComponent(commentHeaderLabel, 2, 0);

    for (int i = 0; i < commentList.size(); i++) {
        final Comment comment = commentList.get(i);

        final Link authorImageLink = GravatarUtil.getGravatarImageLink(comment.getAuthor().getEmailAddress());
        gridLayout.addComponent(authorImageLink, 0, i + 1);

        final Label authorLabel = new Label();
        final String authorName = comment.getAuthor().getFirstName();
        authorLabel.setValue(authorName);
        gridLayout.addComponent(authorLabel, 1, i + 1);

        final Label messageLabel = new Label();
        messageLabel.setValue(comment.getMessage());
        gridLayout.addComponent(messageLabel, 2, i + 1);
    }

}

From source file:org.bubblecloud.ilves.component.flow.AbstractFlowlet.java

License:Apache License

@Override
public final void attach() {
    super.attach();
    this.setSizeFull();

    rootLayout = new GridLayout(1, 2);
    rootLayout.setMargin(false);/*from ww w  .j a  v  a2  s.com*/
    rootLayout.setSpacing(true);
    rootLayout.setSizeFull();
    rootLayout.setRowExpandRatio(0, 0f);
    rootLayout.setRowExpandRatio(1, 1f);

    final HorizontalLayout titleLayout = new HorizontalLayout();
    titleLayout.setMargin(new MarginInfo(true, false, true, false));
    titleLayout.setSpacing(true);

    final Embedded titleIcon = new Embedded(null, getSite().getIcon("view-icon-" + getFlowletKey()));
    titleIcon.setWidth(32, Unit.PIXELS);
    titleIcon.setHeight(32, Unit.PIXELS);
    titleLayout.addComponent(titleIcon);

    final Label titleLabel = new Label("<h1>" + getSite().localize("view-" + getFlowletKey()) + "</h1>",
            ContentMode.HTML);
    titleLayout.addComponent(titleLabel);
    rootLayout.addComponent(titleLayout, 0, 0);

    setCompositionRoot(rootLayout);

    initialize();
}

From source file:org.bubblecloud.ilves.component.grid.Grid.java

License:Apache License

/**
 * Constructs the grid layout.//from w  w  w .  j  av  a2 s  .c om
 * @param table the table
 * @param container the container
 * @param showFilters true if filters should be shown.
 */
private void construct(final Table table, final LazyQueryContainer container, final boolean showFilters) {
    this.table = table;

    table.setImmediate(true);
    table.setSelectable(true);
    table.setBuffered(false);
    table.setColumnCollapsingAllowed(true);
    table.setContainerDataSource(container);
    table.setSizeFull();

    if (showFilters) {
        final GridLayout layout = new GridLayout(1, 2);
        layout.setSpacing(true);
        layout.setRowExpandRatio(0, 0f);
        layout.setRowExpandRatio(1, 1f);

        filterLayout = new HorizontalLayout();
        ((HorizontalLayout) filterLayout).setSpacing(true);

        layout.addComponent(filterLayout, 0, 0);
        layout.addComponent(table, 0, 1);

        setCompositionRoot(layout);
        layout.setSizeFull();
        setSizeFull();
    } else {
        setCompositionRoot(table);
        setSizeFull();
    }
}

From source file:org.bubblecloud.ilves.component.grid.ValidatingEditor.java

License:Apache License

/**
 * Constructor which initializes the form.
 * @param fieldDescriptors The field definitions.
 *///w w  w  .  j av a  2  s  .  co m
public ValidatingEditor(final List<FieldDescriptor> fieldDescriptors) {
    this.fieldDescriptors = fieldDescriptors;

    form = new Form();
    form.setBuffered(true);
    form.setFormFieldFactory(this);
    form.setImmediate(true);
    setCompositionRoot(form);

    formLayout = new GridLayout(3, fieldDescriptors.size());
    formLayout.setSpacing(true);
    formLayout.setMargin(new MarginInfo(true, false, true, false));
    form.setLayout(formLayout);

    fieldIds = new Object[fieldDescriptors.size()];
    fields = new Field[fieldDescriptors.size()];
    fieldLabels = new Label[fieldDescriptors.size()];
    fieldIcons = new Embedded[fieldDescriptors.size()];
    for (int i = 0; i < fieldDescriptors.size(); i++) {
        final FieldDescriptor fieldDescriptor = fieldDescriptors.get(i);
        fieldIds[i] = fieldDescriptor.getId();
        fieldLabels[i] = new Label(fieldDescriptor.getLabel());
        fieldIcons[i] = new Embedded(null, noneIcon);
        fieldIcons[i].setWidth(20, Unit.PIXELS);
        fieldIcons[i].setHeight(20, Unit.PIXELS);

        formLayout.addComponent(fieldLabels[i], 0, i);
        formLayout.addComponent(fieldIcons[i], 2, i);
        formLayout.setComponentAlignment(fieldLabels[i], Alignment.MIDDLE_RIGHT);
    }
}

From source file:org.bubblecloud.ilves.module.audit.AuditLogEntryFlowlet.java

License:Apache License

@Override
public void initialize() {
    entityManager = getSite().getSiteContext().getObject(EntityManager.class);

    final GridLayout gridLayout = new GridLayout(1, 2);
    gridLayout.setSizeFull();//  w ww.  j ava 2 s.  c o m
    gridLayout.setMargin(false);
    gridLayout.setSpacing(true);
    gridLayout.setRowExpandRatio(1, 1f);
    setViewContent(gridLayout);

    auditLogEntryEditor = new ValidatingEditor(
            FieldSetDescriptorRegister.getFieldSetDescriptor(AuditLogEntry.class).getFieldDescriptors());
    auditLogEntryEditor.setReadOnly(true);
    auditLogEntryEditor.setCaption("AuditLogEntry");
    auditLogEntryEditor.addListener(this);
    gridLayout.addComponent(auditLogEntryEditor, 0, 0);

    final HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    gridLayout.addComponent(buttonLayout, 0, 1);

}

From source file:org.bubblecloud.ilves.module.audit.AuditLogFlowlet.java

License:Apache License

@Override
public void initialize() {
    // Get entity manager from site context and prepare container.
    final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class);
    entityContainer = new EntityContainer<AuditLogEntry>(entityManager, true, false, false, AuditLogEntry.class,
            1000, new String[] { "created" }, new boolean[] { false }, "auditLogEntryId");

    // Get descriptors and set container properties.
    final List<FilterDescriptor> filterDescriptors = new ArrayList<FilterDescriptor>();
    filterDescriptors.add(new FilterDescriptor("startTime", "created", getSite().localize("filter-start-time"),
            new TimestampField(), 200, ">=", Date.class, new DateTime().withTimeAtStartOfDay().toDate()));
    filterDescriptors.add(new FilterDescriptor("endTime", "created", getSite().localize("filter-end-time"),
            new TimestampField(), 200, "<=", Date.class,
            new DateTime().withTimeAtStartOfDay().plusDays(1).toDate()));
    final List<FieldDescriptor> fieldDescriptors = FieldSetDescriptorRegister
            .getFieldSetDescriptor(AuditLogEntry.class).getFieldDescriptors();
    ContainerUtil.addContainerProperties(entityContainer, fieldDescriptors);

    // Initialize layout
    final GridLayout gridLayout = new GridLayout(1, 2);
    gridLayout.setSizeFull();//ww w. jav  a 2 s .  c o  m
    gridLayout.setMargin(false);
    gridLayout.setSpacing(true);
    gridLayout.setRowExpandRatio(1, 1f);
    setViewContent(gridLayout);
    final HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.setSizeUndefined();
    gridLayout.addComponent(buttonLayout, 0, 0);

    final Table table = new FormattingTable();
    table.setPageLength(13);

    // Initialize grid
    entityGrid = new Grid(table, entityContainer);
    entityGrid.setFields(fieldDescriptors);
    entityGrid.setFilters(filterDescriptors);
    gridLayout.addComponent(entityGrid, 0, 1);

    final Button viewButton = getSite().getButton("view");
    buttonLayout.addComponent(viewButton);
    viewButton.addClickListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            if (entityGrid.getSelectedItemId() == null) {
                return;
            }
            final AuditLogEntry entity = entityContainer.getEntity(entityGrid.getSelectedItemId());
            final AuditLogEntryFlowlet contentView = getFlow().forward(AuditLogEntryFlowlet.class);
            contentView.edit(entity, false);
        }
    });

}