List of usage examples for com.vaadin.ui Grid setSelectionMode
public GridSelectionModel<T> setSelectionMode(SelectionMode selectionMode)
From source file:annis.gui.admin.CorpusAdminPanel.java
License:Apache License
public CorpusAdminPanel() { corpusContainer.setBeanIdProperty("name"); final Grid corporaGrid = new Grid(corpusContainer); corporaGrid.setSizeFull();//from w ww . j a va2 s . c o m corporaGrid.setSelectionMode(Grid.SelectionMode.MULTI); corporaGrid.setColumns("name", "textCount", "tokenCount", "sourcePath"); corporaGrid.getColumn("textCount").setHeaderCaption("Texts"); corporaGrid.getColumn("tokenCount").setHeaderCaption("Tokens"); corporaGrid.getColumn("sourcePath").setHeaderCaption("Source Path"); Button btDelete = new Button("Delete selected"); btDelete.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { Set<String> selection = new TreeSet<>(); for (Object o : corporaGrid.getSelectedRows()) { selection.add((String) o); } corporaGrid.getSelectionModel().reset(); if (!selection.isEmpty()) { for (CorpusListView.Listener l : listeners) { l.deleteCorpora(selection); } } } }); VerticalLayout layout = new VerticalLayout(btDelete, corporaGrid); layout.setSizeFull(); layout.setExpandRatio(corporaGrid, 1.0f); layout.setSpacing(true); layout.setMargin(new MarginInfo(true, false, false, false)); layout.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER); setContent(layout); setSizeFull(); }
From source file:com.foc.vaadin.gui.components.TableTreeDelegate.java
License:Apache License
public void setAttributes(Attributes attrib) { attributes = attrib;/*from w ww. j av a 2 s. co m*/ FocXMLGuiComponentStatic.applyAttributes((FocXMLGuiComponent) getTreeOrTable(), attributes); if (attributes != null) { String style = attributes.getValue(FXML.ATT_STYLE); if (style != null && !style.isEmpty()) { if (getTable() != null) getTable().addStyleName(style); } String rowSelectionMode = attributes.getValue(FXML.ATT_GRID_SELECTION_MODE); if (rowSelectionMode != null && rowSelectionMode.equals(FXML.VAL_GRID_SELECTION_MODE_MULTI)) { if (getTreeOrTable() instanceof Grid) { Grid grid = (Grid) getTreeOrTable(); grid.setSelectionMode(SelectionMode.MULTI); } } String pageLength = attributes.getValue(FXML.ATT_TREE_TABLE_PAGE_LENGTH); // if(pageLength != null && !pageLength.isEmpty()){ // if(pageLength.equals(FXML.VAL_TREE_TABLE_FIT_SIZE)){ // if(getTreeOrTable() != null && getTreeOrTable().getFocList() != null){ // int listSize = ((Table)getTreeOrTable()).getVisibleItemIds().size(); // if(listSize > 0){ // getTable().setPageLength(listSize); // }else if(listSize == 0){ // getTable().setPageLength(1); // } // getTable().markAsDirty(); // } // }else{ // try{ // getTable().setPageLength(Integer.parseInt(pageLength)); // }catch (Exception e){ // Globals.logException(e); // } // } // } if (pageLength != null && !pageLength.isEmpty()) { if (pageLength.equals(FXML.VAL_TREE_TABLE_FIT_SIZE)) { if (getTreeOrTable() != null && getTreeOrTable().getFocList() != null) { fitTreeToMax(); // FocList list = getTreeOrTable().getFocList(); // int listSize = list.size(); //// if(listSize > 50) listSize = 50; // if(listSize > 0){ // getTable().setPageLength(listSize); // }else if(listSize == 0){ // getTable().setPageLength(1); // } // getTable().markAsDirty(); } } else { try { if (getTable() != null) { getTable().setPageLength(Integer.parseInt(pageLength)); } } catch (Exception e) { Globals.logException(e); } } } String replaceCheckbox = attributes.getValue(FXML.ATT_REPLACE_CHECKBOX); if (!Utils.isStringEmpty(replaceCheckbox) && replaceCheckbox.equalsIgnoreCase("true")) { if (getWrapperLayout() != null) { getWrapperLayout().enableReplace(); } } editingMode = MODE_NOT_EDITABLE; String value = getAttributes().getValue(FXML.ATT_IN_LINE_EDITABLE); if (value != null && (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("onSelection")) && isEditable()) { editingMode = MODE_EDITABLE; if (getWrapperLayout() != null && getWrapperLayout().getDelegate() != null) { getWrapperLayout().getDelegate().setEditable(true); // if(getTable() != null){ // boolean atLEastOneIsEditable = false; // ArrayList<FVTableColumn> arrayList = getVisiblePropertiesArrayList(); // if(arrayList != null){ // for(int i = 0; i < arrayList.size() && !atLEastOneIsEditable; i++){ // FVTableColumn col = arrayList.get(i); // atLEastOneIsEditable = col != null && col.isEditable_ExplicitlyInAttribute(); // } // } // if(atLEastOneIsEditable){ // getTable().addStyleName("inLineEditable"); // } // } } } String withoutConfirmation = attributes.getValue(FXML.ATT_DELETE_WITHOUT_CONFIRMATION); if (withoutConfirmation != null && (withoutConfirmation.toLowerCase().equals("true") || withoutConfirmation.toLowerCase().equals("1"))) { setDeleteWithoutConfirmation(true); } /* if(value != null && value.equalsIgnoreCase("onSelection")){ editingMode = MODE_EDITABLE_ON_SELECTION; getTreeOrTable().setEditable(true); getTable().setImmediate(true); getTable().addValueChangeListener(new Property.ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { // getFocXMLLayout().validationCheckData(); Integer refSelected = (Integer) getTable().getValue(); int refSelectefInt = refSelected != null ? refSelected.intValue() : 0; if(lastRefSelected == 0 || (refSelectefInt != lastRefSelected)){ lastRefSelected = refSelectefInt; Globals.logString("XXXXXXXXXXX Called the Listener in Table Delegate"); if(getFocXMLLayout() != null) getFocXMLLayout().copyGuiToMemory(); getTable().markAsDirty(); getTable().refreshRowCache(); getFocXMLLayout().markAsDirty(); getFocXMLLayout().refresh(); } } }); } */ } }
From source file:com.hack23.cia.web.impl.ui.application.views.common.gridfactory.impl.GridFactoryImpl.java
License:Apache License
@Override public void createBasicBeanItemNestedPropertiesGrid(final AbstractOrderedLayout panelContent, final Indexed datasource, final String caption, final String[] nestedProperties, final Object[] columnOrder, final Object[] hideColumns, final AbstractPageItemRendererClickListener<?> listener, final String actionId, final ListPropertyConverter[] collectionPropertyConverters) { final Grid grid = new Grid(datasource); grid.setCaption(caption);//from ww w.j a v a2s . c o m grid.setSelectionMode(SelectionMode.SINGLE); createNestedProperties(datasource, nestedProperties); configureColumnOrdersAndHiddenFields(columnOrder, hideColumns, grid); configureListeners(listener, grid); setColumnConverters(collectionPropertyConverters, grid); grid.setSizeFull(); grid.setStyleName("Level2Header"); grid.setImmediate(true); grid.setReadOnly(true); createGridCellFilter(columnOrder, grid); panelContent.addComponent(grid); panelContent.setExpandRatio(grid, ContentRatio.GRID); }
From source file:com.rex.components.valo.Tables.java
License:Apache License
static void configure(Table table, Grid grid, boolean footer, boolean sized, boolean expandRatios, boolean stripes, boolean verticalLines, boolean horizontalLines, boolean borderless, boolean headers, boolean compact, boolean small, boolean rowIndex, boolean rowCaption, boolean rowIcon, boolean componentsInRows) { table.setSelectable(true);/*w ww . ja va 2 s . c o m*/ table.setMultiSelect(true); grid.setSelectionMode(SelectionMode.MULTI); table.setSortEnabled(true); for (Column c : grid.getColumns()) { if (!c.getPropertyId().equals("icon")) { c.setSortable(true); } c.setHidable(true); } table.setColumnCollapsingAllowed(true); table.setColumnReorderingAllowed(true); grid.setColumnReorderingAllowed(true); table.setPageLength(6); grid.setHeightByRows(6); table.addActionHandler(ReportEngineUI.getActionHandler()); table.setDragMode(TableDragMode.MULTIROW); table.setDropHandler(new DropHandler() { @Override public AcceptCriterion getAcceptCriterion() { return AcceptAll.get(); } @Override public void drop(DragAndDropEvent event) { Notification.show(event.getTransferable().toString()); } }); table.setColumnAlignment(ReportEngineUI.DESCRIPTION_PROPERTY, Align.RIGHT); table.setColumnAlignment(ReportEngineUI.INDEX_PROPERTY, Align.CENTER); table.removeContainerProperty("textfield"); table.removeGeneratedColumn("textfield"); table.removeContainerProperty("button"); table.removeGeneratedColumn("button"); table.removeContainerProperty("label"); table.removeGeneratedColumn("label"); table.removeContainerProperty("checkbox"); table.removeGeneratedColumn("checkbox"); table.removeContainerProperty("datefield"); table.removeGeneratedColumn("datefield"); table.removeContainerProperty("combobox"); table.removeGeneratedColumn("combobox"); table.removeContainerProperty("optiongroup"); table.removeGeneratedColumn("optiongroup"); table.removeContainerProperty("slider"); table.removeGeneratedColumn("slider"); table.removeContainerProperty("progress"); table.removeGeneratedColumn("progress"); if (componentsInRows) { table.addContainerProperty("textfield", TextField.class, null); table.addGeneratedColumn("textfield", new ColumnGenerator() { @Override public Object generateCell(Table source, Object itemId, Object columnId) { TextField tf = new TextField(); tf.setInputPrompt("Type here"); // tf.addStyleName("compact"); if ((Integer) itemId % 2 == 0) { tf.addStyleName("borderless"); } return tf; } }); table.addContainerProperty("datefield", TextField.class, null); table.addGeneratedColumn("datefield", new ColumnGenerator() { @Override public Object generateCell(Table source, Object itemId, Object columnId) { DateField tf = new DateField(); tf.addStyleName("compact"); if ((Integer) itemId % 2 == 0) { tf.addStyleName("borderless"); } return tf; } }); table.addContainerProperty("combobox", TextField.class, null); table.addGeneratedColumn("combobox", new ColumnGenerator() { @Override public Object generateCell(Table source, Object itemId, Object columnId) { ComboBox tf = new ComboBox(); tf.setInputPrompt("Select"); tf.addStyleName("compact"); if ((Integer) itemId % 2 == 0) { tf.addStyleName("borderless"); } return tf; } }); table.addContainerProperty("button", Button.class, null); table.addGeneratedColumn("button", new ColumnGenerator() { @Override public Object generateCell(Table source, Object itemId, Object columnId) { Button b = new Button("Button"); b.addStyleName("small"); return b; } }); table.addContainerProperty("label", TextField.class, null); table.addGeneratedColumn("label", new ColumnGenerator() { @Override public Object generateCell(Table source, Object itemId, Object columnId) { Label label = new Label("Label component"); label.setSizeUndefined(); label.addStyleName("bold"); return label; } }); table.addContainerProperty("checkbox", TextField.class, null); table.addGeneratedColumn("checkbox", new ColumnGenerator() { @Override public Object generateCell(Table source, Object itemId, Object columnId) { CheckBox cb = new CheckBox(null, true); return cb; } }); table.addContainerProperty("optiongroup", TextField.class, null); table.addGeneratedColumn("optiongroup", new ColumnGenerator() { @Override public Object generateCell(Table source, Object itemId, Object columnId) { OptionGroup op = new OptionGroup(); op.addItem("Male"); op.addItem("Female"); op.addStyleName("horizontal"); return op; } }); table.addContainerProperty("slider", TextField.class, null); table.addGeneratedColumn("slider", new ColumnGenerator() { @Override public Object generateCell(Table source, Object itemId, Object columnId) { Slider s = new Slider(); s.setValue(30.0); return s; } }); table.addContainerProperty("progress", TextField.class, null); table.addGeneratedColumn("progress", new ColumnGenerator() { @Override public Object generateCell(Table source, Object itemId, Object columnId) { ProgressBar bar = new ProgressBar(); bar.setValue(0.7f); return bar; } }); } table.setFooterVisible(footer); if (footer) { table.setColumnFooter(ReportEngineUI.CAPTION_PROPERTY, "caption"); table.setColumnFooter(ReportEngineUI.DESCRIPTION_PROPERTY, "description"); table.setColumnFooter(ReportEngineUI.ICON_PROPERTY, "icon"); table.setColumnFooter(ReportEngineUI.INDEX_PROPERTY, "index"); } if (sized) { table.setWidth("400px"); grid.setWidth("400px"); table.setHeight("300px"); grid.setHeight("300px"); } else { table.setSizeUndefined(); grid.setSizeUndefined(); } if (componentsInRows) { table.setWidth("100%"); } else { table.setWidth(null); } if (expandRatios) { if (!sized) { table.setWidth("100%"); } } table.setColumnExpandRatio(ReportEngineUI.CAPTION_PROPERTY, expandRatios ? 1.0f : 0); table.setColumnExpandRatio(ReportEngineUI.DESCRIPTION_PROPERTY, expandRatios ? 1.0f : 0); if (!stripes) { table.addStyleName("no-stripes"); } else { table.removeStyleName("no-stripes"); } if (!verticalLines) { table.addStyleName("no-vertical-lines"); } else { table.removeStyleName("no-vertical-lines"); } if (!horizontalLines) { table.addStyleName("no-horizontal-lines"); } else { table.removeStyleName("no-horizontal-lines"); } if (borderless) { table.addStyleName("borderless"); } else { table.removeStyleName("borderless"); } if (!headers) { table.addStyleName("no-header"); } else { table.removeStyleName("no-header"); } if (compact) { table.addStyleName("compact"); } else { table.removeStyleName("compact"); } if (small) { table.addStyleName("small"); } else { table.removeStyleName("small"); } if (!rowIndex && !rowCaption && rowIcon) { table.setRowHeaderMode(RowHeaderMode.HIDDEN); } if (rowIndex) { table.setRowHeaderMode(RowHeaderMode.INDEX); } if (rowCaption) { table.setRowHeaderMode(RowHeaderMode.PROPERTY); table.setItemCaptionPropertyId(ReportEngineUI.CAPTION_PROPERTY); } else { table.setItemCaptionPropertyId(null); } if (rowIcon) { table.setRowHeaderMode(RowHeaderMode.ICON_ONLY); table.setItemIconPropertyId(ReportEngineUI.ICON_PROPERTY); } else { table.setItemIconPropertyId(null); } }
From source file:de.datenhahn.vaadin.componentrenderer.demo.ClassicGridWithStaticContainerTab.java
License:Apache License
private void init() { setSizeFull();//from w w w . j ava 2 s .c o m setMargin(true); setSpacing(true); addComponent( new Label("Look at the sourcecode to see the difference between the typed ComponentGrid and using" + " the classic grid")); Grid grid = new Grid(); ComponentCellKeyExtension.extend(grid); focusPreserveExtension = FocusPreserveExtension.extend(grid); DetailsKeysExtension.extend(grid); addComponent(ViewComponents.createEnableDisableCheckBox(grid)); grid.setSelectionMode(Grid.SelectionMode.SINGLE); ((Grid.SingleSelectionModel) grid.getSelectionModel()).setDeselectAllowed(false); grid.setImmediate(true); grid.setSizeFull(); // Initialize Containers BeanItemContainer<StaticCustomer> bc = new BeanItemContainer<>(StaticCustomer.class); grid.setContainerDataSource(bc); // Load the data bc.addAll(StaticCustomerProvider.createDummyData()); // Initialize DetailsGenerator (Caution: the DetailsGenerator is set to null // when grid#setContainerDatasource is called, so make sure you call setDetailsGenerator // after setContainerDatasource grid.setDetailsGenerator(new StaticCustomerDetailsGenerator()); // always display the details column grid.setFrozenColumnCount(1); grid.getColumn(Customer.FOOD).setRenderer(new ComponentRenderer()); grid.setColumns(StaticCustomer.ID, StaticCustomer.FIRST_NAME, StaticCustomer.LAST_NAME, StaticCustomer.FOOD); addComponent(grid); setExpandRatio(grid, 1.0f); }
From source file:dhbw.clippinggorilla.userinterface.views.ArchiveView.java
public ArchiveView() { HorizontalLayout optionsLayout = new HorizontalLayout(); optionsLayout.setWidth("100%"); Grid<Clipping> gridClippings = new Grid<>(); Set<Clipping> clippings = ClippingUtils.getUserClippings(UserUtils.getCurrent(), LocalDate.now(ZoneId.of("Europe/Berlin"))); gridClippings.setItems(clippings);//from w w w . j a v a 2 s. c om InlineDateTimeField datePicker = new InlineDateTimeField(); datePicker.setValue(LocalDateTime.now(ZoneId.of("Europe/Berlin"))); datePicker.setLocale(Locale.GERMANY); datePicker.setResolution(DateTimeResolution.DAY); datePicker.addValueChangeListener(date -> { Set<Clipping> clippingsOfDate = ClippingUtils.getUserClippings(UserUtils.getCurrent(), date.getValue().toLocalDate()); gridClippings.setItems(clippingsOfDate); gridClippings.getDataProvider().refreshAll(); }); DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM); formatter.withZone(ZoneId.of("Europe/Berlin")); Column columnTime = gridClippings.addColumn(c -> { return c.getDate().format(formatter); }); Language.setCustom(Word.TIME, s -> columnTime.setCaption(s)); Column columnAmountArticles = gridClippings.addColumn(c -> { long amountArticles = c.getArticles().values().stream().flatMap(l -> l.stream()).count(); amountArticles += c.getArticlesFromGroup().values().stream().flatMap(l -> l.stream()).count(); if (amountArticles != 1) { return amountArticles + " " + Language.get(Word.ARTICLES); } else { return amountArticles + " " + Language.get(Word.ARTICLE); } }); Language.setCustom(Word.ARTICLES, s -> { columnAmountArticles.setCaption(s); gridClippings.getDataProvider().refreshAll(); }); gridClippings.setHeight("100%"); gridClippings.setSelectionMode(Grid.SelectionMode.SINGLE); gridClippings.addSelectionListener(c -> { if (c.getFirstSelectedItem().isPresent()) { currentClipping = c.getFirstSelectedItem().get(); showClippingBy(currentClipping, currentSort); } }); optionsLayout.addComponents(datePicker, gridClippings); optionsLayout.setComponentAlignment(datePicker, Alignment.BOTTOM_CENTER); optionsLayout.setComponentAlignment(gridClippings, Alignment.BOTTOM_RIGHT); optionsLayout.setExpandRatio(gridClippings, 5); VerticalLayout sortLayout = new VerticalLayout(); comboBoxSortOptions = new ComboBox<>(Language.get(Word.SORT_BY)); Language.setCustom(Word.SORT_BY, s -> { comboBoxSortOptions.setCaption(s); comboBoxSortOptions.getDataProvider().refreshAll(); }); comboBoxSortOptions.setItems(EnumSet.allOf(ClippingView.SortOptions.class)); comboBoxSortOptions.setItemCaptionGenerator(s -> s.getName()); comboBoxSortOptions.setItemIconGenerator(s -> s.getIcon()); comboBoxSortOptions.setValue(currentSort); comboBoxSortOptions.setTextInputAllowed(false); comboBoxSortOptions.setEmptySelectionAllowed(false); comboBoxSortOptions.addStyleName("comboboxsort"); comboBoxSortOptions.addValueChangeListener(e -> { currentSort = e.getValue(); showClippingBy(currentClipping, currentSort); }); comboBoxSortOptions.setVisible(false); sortLayout.setMargin(false); sortLayout.setSpacing(false); sortLayout.addComponent(comboBoxSortOptions); clippingArticlesLayout = new VerticalLayout(); clippingArticlesLayout.setSpacing(true); clippingArticlesLayout.setMargin(false); clippingArticlesLayout.setSizeFull(); addComponents(optionsLayout, sortLayout, clippingArticlesLayout); }
From source file:facs.components.Statistics.java
License:Open Source License
private Component initialGrid() { VerticalLayout gridLayout = new VerticalLayout(); createInvoice.setEnabled(false);//from www. j a va2 s . co m downloadInvoice.setEnabled(false); String buttonRefreshTitle = "Refresh"; Button refresh = new Button(buttonRefreshTitle); refresh.setIcon(FontAwesome.REFRESH); refresh.setDescription("Click here to reload the data from the database!"); refresh.addStyleName(ValoTheme.BUTTON_FRIENDLY); refresh.addClickListener(new ClickListener() { private static final long serialVersionUID = -3610721151565496269L; @Override public void buttonClick(ClickEvent event) { refreshDataSources(); } }); Date dNow = new Date(); SimpleDateFormat ft = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss"); System.out.println(ft.format(dNow) + " INFO Statistics accessed! - User: " + LiferayAndVaadinUtils.getUser().getScreenName()); // Add some generated properties IndexedContainer container = getEmptyContainer(); gpcontainer = new GeneratedPropertyContainer(container); Grid grid = new Grid(gpcontainer); grid.setWidth("100%"); setRenderers(grid); fillRows(grid); // compute total costs float totalCosts = 0.0f; for (Object itemId : gpcontainer.getItemIds()) totalCosts += ((Number) gpcontainer.getContainerProperty(itemId, costCaption).getValue()).floatValue(); // compute total time in milliseconds long total = 0; for (Object itemId : gpcontainer.getItemIds()) { long s = ((Date) gpcontainer.getContainerProperty(itemId, startCaption).getValue()).getTime(); long e = ((Date) gpcontainer.getContainerProperty(itemId, endCaption).getValue()).getTime(); total += e - s; } // set footer to contain total cost and time in hours:minutes FooterRow footer = grid.appendFooterRow(); FooterCell footerCellCost = footer.getCell(costCaption); footerCellCost.setText(String.format("%1$.2f total", totalCosts)); FooterCell footerCellEnd = footer.getCell(endCaption); footerCellEnd.setText(Formatter.toHoursAndMinutes(total)); // "%1$.0f hours" // Set up a filter for all columns HeaderRow filterRow = grid.appendHeaderRow(); addRowFilter(filterRow, deviceCaption, container, footer, gpcontainer); addRowFilter(filterRow, kostenstelleCaption, container, footer, gpcontainer); Label infoLabel = new Label( DBManager.getDatabaseInstance().getUserNameByUserID(LiferayAndVaadinUtils.getUser().getScreenName()) + " " + LiferayAndVaadinUtils.getUser().getScreenName()); infoLabel.addStyleName("h4"); // createInvoice.setSizeFull(); // downloadInvoice.setSizeFull(); gridLayout.setWidth("100%"); gridLayout.setCaption("Statistics"); // add components to the grid layout // gridLayout.addComponent(infoLabel, 0, 0, 3, 0); // gridLayout.addComponent(grid, 0, 1, 5, 1); // gridLayout.addComponent(createInvoice, 0, 3); // gridLayout.addComponent(downloadInvoice, 1, 3); gridLayout.addComponent(grid); gridLayout.addComponent(refresh); gridLayout.addComponent(createInvoice); gridLayout.addComponent(downloadInvoice); gridLayout.setMargin(true); gridLayout.setSpacing(true); // grid.setEditorEnabled(true); grid.setSelectionMode(SelectionMode.SINGLE); grid.addSelectionListener(new SelectionListener() { /** * */ private static final long serialVersionUID = -2683274060620429050L; @Override public void select(SelectionEvent event) { // Notification.show("Select row: " + grid.getSelectedRow() + " Name: " // + gpcontainer.getContainerProperty(grid.getSelectedRow(), nameCaption).getValue()); downloadInvoice.setEnabled(false); ReceiverPI = (String) gpcontainer.getContainerProperty(grid.getSelectedRow(), nameCaption) .getValue(); createInvoice.setEnabled(true); } }); createInvoice.addClickListener(new ClickListener() { /** * */ private static final long serialVersionUID = 5512585967145932560L; private File bill; private FileDownloader fileDownloader; @Override public void buttonClick(ClickEvent event) { String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath(); Paths.get(basepath, "WEB-INF/billingTemplates"); // System.out.println("Basepath: " + basepath); try { int setUserId = DBManager.getDatabaseInstance().findUserByFullName(ReceiverPI); if (setUserId > 0) { Billing billing = new Billing(Paths.get(basepath, "WEB-INF/billingTemplates").toFile(), "Angebot.tex"); UserBean user = setUserId > 0 ? DBManager.getDatabaseInstance().getUserById(setUserId) : null; billing.setReceiverPI(ReceiverPI); billing.setReceiverInstitution(user.getInstitute()); billing.setReceiverStreet(user.getStreet()); billing.setReceiverPostalCode(user.getPostcode()); billing.setReceiverCity(user.getCity()); billing.setSenderName("Dr. rer. nat. Stella Autenrieth"); billing.setSenderFunction("Leiterin"); billing.setSenderPostalCode("72076"); billing.setSenderCity("Tbingen"); billing.setSenderStreet("Otfried-Mller-Strae 10"); billing.setSenderPhone("+49 (0) 7071 29-83156"); billing.setSenderEmail("stella.autenrieth@med.uni-tuebingen.de"); billing.setSenderUrl("www.medizin.uni-tuebingen.de"); billing.setSenderFaculty("Medizinischen Fakultt"); if (user.getKostenstelle() != null) billing.setProjectDescription("Kostenstelle: " + user.getKostenstelle()); else billing.setProjectDescription("Keine kostenstelle verfgbar."); billing.setProjectShortDescription("Dieses Angebot beinhaltet jede Menge Extras."); if (user.getProject() != null) billing.setProjectNumber("Kostenstelle: " + user.getKostenstelle()); else billing.setProjectNumber("Keine project nummer verfgbar."); float cost = ((Number) gpcontainer.getContainerProperty(grid.getSelectedRow(), costCaption) .getValue()).floatValue(); long s = ((Date) gpcontainer.getContainerProperty(grid.getSelectedRow(), startCaption) .getValue()).getTime(); long e = ((Date) gpcontainer.getContainerProperty(grid.getSelectedRow(), endCaption) .getValue()).getTime(); long timeFrame = e - s; Date start = ((Date) gpcontainer.getContainerProperty(grid.getSelectedRow(), startCaption) .getValue()); SimpleDateFormat ft = new SimpleDateFormat("dd.MM.yyyy"); String date = ft.format(start); String description = "No Description is Available"; String time_frame = Formatter.toHoursAndMinutes(timeFrame); ArrayList<CostEntry> entries = new ArrayList<CostEntry>(); entries.add(billing.new CostEntry(date, time_frame, description, cost)); billing.setCostEntries(entries); float totalCosts = 0.0f; // calculates the total cost of items // for (Object itemId : gpcontainer.getItemIds()) { // totalCosts += // ((Number) gpcontainer.getContainerProperty(itemId, costCaption).getValue()) // .floatValue(); // } totalCosts = ((Number) gpcontainer.getContainerProperty(grid.getSelectedRow(), costCaption) .getValue()).floatValue(); billing.setTotalCost(String.format("%1$.2f", totalCosts)); bill = billing.createPdf(); // System.out.println(bill.getAbsolutePath()); if (fileDownloader != null) downloadInvoice.removeExtension(fileDownloader); fileDownloader = new FileDownloader(new FileResource(bill)); fileDownloader.extend(downloadInvoice); downloadInvoice.setEnabled(true); showSuccessfulNotification("Congratulations!", "Invoice is created and available for download."); downloadInvoice.setEnabled(true); } else { createInvoice.setEnabled(false); downloadInvoice.setEnabled(false); showErrorNotification("No such user found!", "An error occured while trying to create the invoice. The common problem occurs to be: this no such user in the database."); } } catch (Exception e) { showErrorNotification("What the heck!", "An error occured while trying to create the invoice. The common problem occurs to be: this no such user or it can not run program 'pdflatex'."); e.printStackTrace(); } // for all entries /* * try { Billing billing = new Billing(Paths.get(basepath, * "WEB-INF/billingTemplates").toFile(), "Angebot.tex"); * billing.setRecieverInstitution("BER - Berliner Flughafen"); * billing.setRecieverPI("Klaus Something"); * billing.setRecieverStreet("am berliner flughafen 12"); * billing.setRecieverPostalCode("D-12345"); billing.setRecieverCity("Berlin"); * * billing.setSenderName("Dr. rer. nat. Stella Autenrieth"); * billing.setSenderFunction("Leiterin"); billing.setSenderPostalCode("72076"); * billing.setSenderCity("Tbingen"); billing.setSenderStreet("Otfried-Mller-Strae 10"); * billing.setSenderPhone("+49 (0) 7071 29-83156"); * billing.setSenderEmail("stella.autenrieth@med.uni-tuebingen.de"); * billing.setSenderUrl("www.medizin.uni-tuebingen.de"); * billing.setSenderFaculty("Medizinischen Fakultt"); * * billing.setProjectDescription("Dieses Angebot beinhaltet jede Menge Extras."); * billing.setProjectShortDescription("jede Menge Extras."); * billing.setProjectNumber("QA2014016"); * * ArrayList<CostEntry> entries = new ArrayList<CostEntry>(); for (Object itemId : * gpcontainer.getItemIds()) { float cost = ((Number) * gpcontainer.getContainerProperty(itemId, costCaption).getValue()) .floatValue(); long s = * ((Date) gpcontainer.getContainerProperty(itemId, startCaption).getValue()) .getTime(); * long e = ((Date) gpcontainer.getContainerProperty(itemId, * endCaption).getValue()).getTime(); long timeFrame = e - s; Date start = ((Date) * gpcontainer.getContainerProperty(itemId, startCaption).getValue()); SimpleDateFormat ft = * new SimpleDateFormat("dd.MM.yyyy"); String date = ft.format(start); String description = * "No Description is Available"; String time_frame = * Formatter.toHoursAndMinutes(timeFrame); entries.add(billing.new CostEntry(date, * time_frame, description, cost)); } billing.setCostEntries(entries); float totalCosts = * 0.0f; for (Object itemId : gpcontainer.getItemIds()) { totalCosts += ((Number) * gpcontainer.getContainerProperty(itemId, costCaption).getValue()) .floatValue(); } * * billing.setTotalCost(String.format("%1$.2f", totalCosts)); * * bill = billing.createPdf(); System.out.println(bill.getAbsolutePath()); if * (fileDownloader != null) downloadBill.removeExtension(fileDownloader); fileDownloader = * new FileDownloader(new FileResource(bill)); fileDownloader.extend(downloadBill); * downloadBill.setEnabled(true); showSuccessfulNotification("Congratulations!", * "Invoice is created and available for download."); } catch (Exception e) { * showErrorNotification( "What the heck!", * "An error occured while trying to create the invoice. The common problem occurs to be: cannot run program 'pdflatex'" * ); e.printStackTrace(); } */ } }); return gridLayout; }
From source file:facs.components.Statistics.java
License:Open Source License
private Component newMatchedGrid() { Button createInvoiceMatched = new Button("Create Invoice"); Button downloadInvoiceMatched = new Button("Download Invoice"); String buttonRefreshTitle = "Refresh"; Button refreshMatched = new Button(buttonRefreshTitle); refreshMatched.setIcon(FontAwesome.REFRESH); refreshMatched.setDescription("Click here to reload the data from the database!"); refreshMatched.addStyleName(ValoTheme.BUTTON_FRIENDLY); createInvoiceMatched.setEnabled(false); downloadInvoiceMatched.setEnabled(false); Grid matchedGrid; refreshMatched.addClickListener(new ClickListener() { private static final long serialVersionUID = -3610721151565496269L; @Override// w w w .j av a 2 s .c o m public void buttonClick(ClickEvent event) { refreshDataSources(); } }); IndexedContainer mcontainer = getEmptyContainer(); GeneratedPropertyContainer mpc = new GeneratedPropertyContainer(mcontainer); VerticalLayout matchedLayout = new VerticalLayout(); matchedGrid = new Grid(mpc); setRenderers(matchedGrid); fillMatchedRows(matchedGrid); // compute total costs float totalCosts = 0.0f; for (Object itemId : mpc.getItemIds()) totalCosts += ((Number) mpc.getContainerProperty(itemId, costCaption).getValue()).floatValue(); // compute total time in milliseconds long total = 0; for (Object itemId : mpc.getItemIds()) { long s = ((Date) mpc.getContainerProperty(itemId, startCaption).getValue()).getTime(); long e = ((Date) mpc.getContainerProperty(itemId, endCaption).getValue()).getTime(); total += e - s; } // set footer to contain total cost and time in hours:minutes FooterRow footer = matchedGrid.appendFooterRow(); FooterCell footerCellCost = footer.getCell(costCaption); footerCellCost.setText(String.format("%1$.2f total", totalCosts)); FooterCell footerCellEnd = footer.getCell(endCaption); footerCellEnd.setText(Formatter.toHoursAndMinutes(total)); // "%1$.0f hours" // Set up a filter for all columns HeaderRow filterRow = matchedGrid.appendHeaderRow(); addRowFilter(filterRow, deviceCaption, mcontainer, footer, mpc); addRowFilter(filterRow, kostenstelleCaption, mcontainer, footer, mpc); matchedLayout.setMargin(true); matchedLayout.setSpacing(true); // devicesGrid.setWidth("100%"); matchedGrid.setSizeFull(); matchedGrid.setSelectionMode(SelectionMode.SINGLE); matchedLayout.addComponent(matchedGrid); matchedGrid.setSelectionMode(SelectionMode.SINGLE); matchedGrid.addSelectionListener(new SelectionListener() { /** * */ private static final long serialVersionUID = -2683274060620429050L; @Override public void select(SelectionEvent event) { // Notification.show("Select row: " + grid.getSelectedRow() + " Name: " // + gpcontainer.getContainerProperty(grid.getSelectedRow(), nameCaption).getValue()); downloadInvoiceMatched.setEnabled(false); ReceiverPI = (String) mpc.getContainerProperty(matchedGrid.getSelectedRow(), nameCaption) .getValue(); createInvoiceMatched.setEnabled(true); } }); createInvoiceMatched.addClickListener(new ClickListener() { private File bill; private FileDownloader fileDownloader; @Override public void buttonClick(ClickEvent event) { String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath(); Paths.get(basepath, "WEB-INF/billingTemplates"); // System.out.println("Basepath: " + basepath); try { int setUserId = DBManager.getDatabaseInstance().findUserByFullName(ReceiverPI); if (setUserId > 0) { Billing billing = new Billing(Paths.get(basepath, "WEB-INF/billingTemplates").toFile(), "Angebot.tex"); UserBean user = setUserId > 0 ? DBManager.getDatabaseInstance().getUserById(setUserId) : null; billing.setReceiverPI(ReceiverPI); billing.setReceiverInstitution(user.getInstitute()); billing.setReceiverStreet(user.getStreet()); billing.setReceiverPostalCode(user.getPostcode()); billing.setReceiverCity(user.getCity()); billing.setSenderName("Dr. rer. nat. Stella Autenrieth"); billing.setSenderFunction("Leiterin"); billing.setSenderPostalCode("72076"); billing.setSenderCity("Tbingen"); billing.setSenderStreet("Otfried-Mller-Strae 10"); billing.setSenderPhone("+49 (0) 7071 29-83156"); billing.setSenderEmail("stella.autenrieth@med.uni-tuebingen.de"); billing.setSenderUrl("www.medizin.uni-tuebingen.de"); billing.setSenderFaculty("Medizinischen Fakultt"); if (user.getKostenstelle() != null) billing.setProjectDescription("Kostenstelle: " + user.getKostenstelle()); else billing.setProjectDescription("Keine kostenstelle verfgbar."); billing.setProjectShortDescription("Dieses Angebot beinhaltet jede Menge Extras."); if (user.getProject() != null) billing.setProjectNumber("Kostenstelle: " + user.getKostenstelle()); else billing.setProjectNumber("Keine project nummer verfgbar."); float cost = ((Number) mpc.getContainerProperty(matchedGrid.getSelectedRow(), costCaption) .getValue()).floatValue(); long s = ((Date) mpc.getContainerProperty(matchedGrid.getSelectedRow(), startCaption) .getValue()).getTime(); long e = ((Date) mpc.getContainerProperty(matchedGrid.getSelectedRow(), endCaption) .getValue()).getTime(); long timeFrame = e - s; Date start = ((Date) mpc.getContainerProperty(matchedGrid.getSelectedRow(), startCaption) .getValue()); SimpleDateFormat ft = new SimpleDateFormat("dd.MM.yyyy"); String date = ft.format(start); String description = "No Description is Available"; String time_frame = Formatter.toHoursAndMinutes(timeFrame); ArrayList<CostEntry> entries = new ArrayList<CostEntry>(); entries.add(billing.new CostEntry(date, time_frame, description, cost)); billing.setCostEntries(entries); float totalCosts = 0.0f; totalCosts = ((Number) mpc.getContainerProperty(matchedGrid.getSelectedRow(), costCaption) .getValue()).floatValue(); billing.setTotalCost(String.format("%1$.2f", totalCosts)); bill = billing.createPdf(); // System.out.println(bill.getAbsolutePath()); if (fileDownloader != null) downloadInvoiceMatched.removeExtension(fileDownloader); fileDownloader = new FileDownloader(new FileResource(bill)); fileDownloader.extend(downloadInvoiceMatched); downloadInvoiceMatched.setEnabled(true); showSuccessfulNotification("Congratulations!", "Invoice is created and available for download."); downloadInvoiceMatched.setEnabled(true); } else { createInvoiceMatched.setEnabled(false); downloadInvoiceMatched.setEnabled(false); showErrorNotification("No such user found!", "An error occured while trying to create the invoice. The common problem occurs to be: this no such user in the database."); } } catch (Exception e) { showErrorNotification("What the heck!", "An error occured while trying to create the invoice. The common problem occurs to be: this no such user or it can not run program 'pdflatex'."); e.printStackTrace(); } } }); matchedLayout.addComponent(refreshMatched); matchedLayout.addComponent(createInvoiceMatched); matchedLayout.addComponent(downloadInvoiceMatched); return matchedLayout; }
From source file:fi.semantum.strategia.Updates.java
License:Open Source License
private static void updateQueryGrid(final Main main, final FilterState state) { main.gridPanelLayout.removeAllComponents(); main.gridPanelLayout.setMargin(false); final List<String> keys = state.reportColumns; if (keys.isEmpty()) { Label l = new Label("Kysely ei tuottanut yhtn tulosta."); l.addStyleName(ValoTheme.LABEL_BOLD); l.addStyleName(ValoTheme.LABEL_HUGE); main.gridPanelLayout.addComponent(l); return;// w w w. jav a 2s .co m } final IndexedContainer container = new IndexedContainer(); for (String key : keys) { container.addContainerProperty(key, String.class, ""); } rows: for (Map<String, ReportCell> map : state.report) { Object item = container.addItem(); for (String key : keys) if (map.get(key) == null) continue rows; for (Map.Entry<String, ReportCell> entry : map.entrySet()) { @SuppressWarnings("unchecked") com.vaadin.data.Property<String> p = container.getContainerProperty(item, entry.getKey()); p.setValue(entry.getValue().get()); } } HorizontalLayout hl = new HorizontalLayout(); hl.setWidth("100%"); final TextField filter = new TextField(); filter.addStyleName(ValoTheme.TEXTFIELD_TINY); filter.setInputPrompt("rajaa hakutuloksia - kirjoitetun sanan tulee lyty rivin teksteist"); filter.setWidth("100%"); final Image clipboard = new Image(); clipboard.setSource(new ThemeResource("page_white_excel.png")); clipboard.setHeight("24px"); clipboard.setWidth("24px"); hl.addComponent(filter); hl.setExpandRatio(filter, 1.0f); hl.setComponentAlignment(filter, Alignment.BOTTOM_CENTER); hl.addComponent(clipboard); hl.setComponentAlignment(clipboard, Alignment.BOTTOM_CENTER); hl.setExpandRatio(clipboard, 0.0f); main.gridPanelLayout.addComponent(hl); main.gridPanelLayout.setExpandRatio(hl, 0f); filter.addValueChangeListener(new ValueChangeListener() { private static final long serialVersionUID = 3033918399018888150L; @Override public void valueChange(ValueChangeEvent event) { container.removeAllContainerFilters(); container.addContainerFilter(new QueryFilter(filter.getValue(), true, false)); } }); AbsoluteLayout abs = new AbsoluteLayout(); abs.setSizeFull(); final Grid queryGrid = new Grid(container); queryGrid.setSelectionMode(SelectionMode.NONE); queryGrid.setHeightMode(HeightMode.CSS); queryGrid.setHeight("100%"); queryGrid.setWidth("100%"); for (String key : keys) { Column col = queryGrid.getColumn(key); col.setExpandRatio(1); } abs.addComponent(queryGrid); OnDemandFileDownloader dl = new OnDemandFileDownloader(new OnDemandStreamSource() { private static final long serialVersionUID = 981769438054780731L; File f; Date date = new Date(); @Override public InputStream getStream() { String uuid = UUID.randomUUID().toString(); File printing = new File(Main.baseDirectory(), "printing"); f = new File(printing, uuid + ".xlsx"); Workbook w = new XSSFWorkbook(); Sheet sheet = w.createSheet("Sheet1"); Row header = sheet.createRow(0); for (int i = 0; i < keys.size(); i++) { Cell cell = header.createCell(i); cell.setCellValue(keys.get(i)); } int row = 1; rows: for (Map<String, ReportCell> map : state.report) { for (String key : keys) if (map.get(key) == null) continue rows; Row r = sheet.createRow(row++); int column = 0; for (int i = 0; i < keys.size(); i++) { Cell cell = r.createCell(column++); ReportCell rc = map.get(keys.get(i)); cell.setCellValue(rc.getLong()); } } try { FileOutputStream s = new FileOutputStream(f); w.write(s); s.close(); } catch (Exception e) { e.printStackTrace(); } try { return new FileInputStream(f); } catch (FileNotFoundException e) { e.printStackTrace(); } throw new IllegalStateException(); } @Override public void onRequest() { // TODO Auto-generated method stub } @Override public long getFileSize() { return f.length(); } @Override public String getFileName() { return "Strategiakartta_" + Utils.dateString(date) + ".xlsx"; } }); dl.getResource().setCacheTime(0); dl.extend(clipboard); main.gridPanelLayout.addComponent(abs); main.gridPanelLayout.setExpandRatio(abs, 1f); }
From source file:net.sourceforge.javydreamercsw.validation.manager.web.admin.AdminScreenProvider.java
License:Apache License
private Component displayIssueTypes() { VerticalLayout vl = new VerticalLayout(); Grid grid = new Grid(TRANSLATOR.translate(ISSUE_TYPE)); BeanItemContainer<IssueType> types = new BeanItemContainer<>(IssueType.class); types.addAll(new IssueTypeJpaController(DataBaseManager.getEntityManagerFactory()).findIssueTypeEntities()); grid.setContainerDataSource(types);/*from ww w . ja v a 2 s. com*/ grid.setSelectionMode(SelectionMode.SINGLE); grid.setColumns("typeName", DESC); Grid.Column name = grid.getColumn("typeName"); name.setHeaderCaption(TRANSLATOR.translate("general.name")); name.setConverter(new TranslationConverter()); Grid.Column desc = grid.getColumn(DESC); desc.setHeaderCaption(TRANSLATOR.translate("general.description")); desc.setConverter(new TranslationConverter()); grid.setSizeFull(); vl.addComponent(grid); grid.setHeightMode(HeightMode.ROW); grid.setHeightByRows(types.size() > 5 ? 5 : types.size()); //Menu HorizontalLayout hl = new HorizontalLayout(); Button add = new Button(TRANSLATOR.translate("general.create")); add.addClickListener(listener -> { VMWindow w = new VMWindow(); w.setContent(new IssueTypeComponent(new IssueType(), true)); ((VMUI) UI.getCurrent()).addWindow(w); w.addCloseListener(l -> { ((VMUI) UI.getCurrent()).updateScreen(); }); }); hl.addComponent(add); Button delete = new Button(TRANSLATOR.translate("general.delete")); delete.setEnabled(false); delete.addClickListener(listener -> { IssueType selected = (IssueType) ((SingleSelectionModel) grid.getSelectionModel()).getSelectedRow(); if (selected != null && selected.getId() >= 1000) { try { new IssueTypeJpaController(DataBaseManager.getEntityManagerFactory()).destroy(selected.getId()); ((VMUI) UI.getCurrent()).updateScreen(); } catch (IllegalOrphanException | NonexistentEntityException ex) { LOG.log(Level.SEVERE, null, ex); Notification.show(TRANSLATOR.translate(DELETE_ERROR), TRANSLATOR.translate(DELETE_ERROR), Notification.Type.ERROR_MESSAGE); } } }); hl.addComponent(delete); vl.addComponent(hl); grid.addSelectionListener(event -> { // Java 8 // Get selection from the selection model IssueType selected = (IssueType) ((SingleSelectionModel) grid.getSelectionModel()).getSelectedRow(); //Only delete custom ones. delete.setEnabled(selected != null && selected.getId() >= 1000); }); return vl; }