2017-02-09 76 views
0

我正在嘗試設置更新vaadin中的bean項目的組合框值。但是當我打開它時,組合框選定的值爲空。我如何綁定價值?如何使用beanitemcontainer設置vaadin組合框值?

BeanItemContainer<Company> itemContainer = new BeanItemContainer<Company>(Company.class); 
    itemContainer.addAll(companyService.getAllCompanies()); 

    cbxCompanyName = new ComboBox("Company Name", itemContainer); 
    cbxCompanyName.setWidth("50%"); 
    cbxCompanyName.setNullSelectionAllowed(false); 
    cbxCompanyName.setItemCaptionMode(ItemCaptionMode.PROPERTY); 
    cbxCompanyName.setImmediate(true); 
    cbxCompanyName.setItemCaptionPropertyId("companyName"); 
    cbxCompanyName.setNewItemsAllowed(false); 
    details.addComponent(cbxCompanyName); 

    cbxCompanyName.setValue(admin.getCompany()); 

enter image description here

+0

你有沒有在Company類上實現equals和hashcode? –

回答

1

enter image description here

下面是代碼:

@Theme("mytheme") 
public class MyUI extends UI { 

    @Override 
    protected void init(VaadinRequest vaadinRequest) { 
     final VerticalLayout layout = new VerticalLayout(); 
     layout.setMargin(true); 
     layout.setSpacing(true); 
     setContent(layout); 

     //cache the beans 
     ArrayList<MyBean> beans = getBeans(); 

     BeanItemContainer container = new BeanItemContainer<>(MyBean.class, beans); 

     ComboBox combo = new ComboBox("My Combo");    
     combo.setItemCaptionMode(AbstractSelect.ItemCaptionMode.PROPERTY); 
     combo.setItemCaptionPropertyId("field"); 
     combo.setContainerDataSource(container); 

     //select programmatically 
     combo.select(beans.get(1));//this is the key idea! Provide the same bean from cache, for selection. 

     layout.addComponent(combo); 
    } 

    @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true) 
    @VaadinServletConfiguration(ui = MyUI.class, productionMode = false) 
    public static class MyUIServlet extends VaadinServlet { 
    } 

    public class MyBean { 

     private final int id; 
     private final String field; 

     public MyBean(int id, String field) { 
      this.id = id; 
      this.field = field; 
     } 

     public int getId() { 
      return id; 
     } 

     public String getField() { 
      return field; 
     } 

    } 

    public ArrayList<MyBean> getBeans() { 
     ArrayList<MyBean> beans = new ArrayList<>(); 

     MyBean bean = new MyBean(1, "Vikrant"); 
     beans.add(bean); 

     bean = new MyBean(2, "John"); 
     beans.add(bean); 

     bean = new MyBean(3, "Rahul"); 
     beans.add(bean); 

     return beans; 
    } 
+0

感謝您的回覆,這對我來說是個好主意。 –

0

這裏是我的解決方案;

cbxCompany.select(cbxCompany.getItemIds().toArray()[getCompanyIndex()]); 
    /** 
    * 
    * 
    **/ 
    for (int i = 0; i < cbxCompany.getItemIds().toArray().length; i++) { 
       if (((Company) cbxCompany.getItemIds().toArray()[i]).getCompanyID() == admin.getCompany().getCompanyID()) { 
        return i; 
       } 
      }