You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UsingCustomNewItemHandlerInSelect.java 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.vaadin.tests;
  2. import java.util.Random;
  3. import com.vaadin.ui.CustomComponent;
  4. import com.vaadin.ui.Panel;
  5. import com.vaadin.ui.VerticalLayout;
  6. import com.vaadin.v7.data.Item;
  7. import com.vaadin.v7.ui.AbstractSelect;
  8. import com.vaadin.v7.ui.Select;
  9. public class UsingCustomNewItemHandlerInSelect extends CustomComponent {
  10. private final Select select = new Select();
  11. public static Random random = new Random(1);
  12. private static int sequence = 0;
  13. public UsingCustomNewItemHandlerInSelect() {
  14. VerticalLayout pl = new VerticalLayout();
  15. pl.setMargin(true);
  16. final Panel panel = new Panel("Select demo", pl);
  17. pl.addComponent(select);
  18. select.setCaption("Select component");
  19. select.setImmediate(true);
  20. select.addContainerProperty("CAPTION", String.class, "");
  21. select.setItemCaptionMode(Select.ITEM_CAPTION_MODE_PROPERTY);
  22. select.setItemCaptionPropertyId("CAPTION");
  23. select.setNewItemsAllowed(true);
  24. select.setNewItemHandler(new MyNewItemHandler());
  25. populateSelect();
  26. setCompositionRoot(panel);
  27. }
  28. public void populateSelect() {
  29. final String[] names = { "John", "Mary", "Joe", "Sarah", "Jeff", "Jane",
  30. "Peter", "Marc", "Josie", "Linus" };
  31. for (int j = 0; j < 4; j++) {
  32. Integer id = new Integer(sequence++);
  33. Item item = select.addItem(id);
  34. item.getItemProperty("CAPTION").setValue(
  35. id + ": " + names[random.nextInt() % names.length]);
  36. }
  37. }
  38. public class MyNewItemHandler implements AbstractSelect.NewItemHandler {
  39. @Override
  40. public void addNewItem(String newItemCaption) {
  41. // here could be db insert or other backend operation
  42. Integer id = new Integer(sequence++);
  43. Item item = select.addItem(id);
  44. item.getItemProperty("CAPTION")
  45. .setValue(id + ": " + newItemCaption);
  46. select.setValue(id);
  47. }
  48. }
  49. }