2017-01-27 52 views
1

我有BeanItemContainer,這是我通過JDBC從數據庫中加載:如何綁定BeanItemContainer到組合框

BeanItemContainer myBeans = new BeanItemContainer<>(MyBean.class, mybeanDao.findAll()); 

,這是我如何安裝到組合框:

Combobox combo = new Combobox(); 
combobox.setContainerDataSource(myBeans); 

到目前爲止,一切都很好。我收到了我想要的,但現在我有一個問題 - 如何獲得已選擇的實際ID?這必須是同步的(在combobox中選擇的id是數據庫中的實際條目)。

我不知道,該如何解決這個問題

請幫

PS爲myBean類

public class MyBean { 

    private Long id; 
    private String field1; 

*** getters /setters *** 
    and toString() {} method 
} 

回答

2

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); 

    BeanItemContainer myBeans = new BeanItemContainer<>(MyBean.class, getBeans()); 

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

    combo.addValueChangeListener(new Property.ValueChangeListener() { 
     @Override 
     public void valueChange(Property.ValueChangeEvent event) { 
      MyBean bean = (MyBean) combo.getValue(); 

      Notification notif = new Notification("Selected Bean Id: "+bean.getId(), Notification.Type.TRAY_NOTIFICATION); 
      notif.setPosition(Position.TOP_CENTER); 
      notif.show(Page.getCurrent()); 
     } 
    }); 

    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 Long id; 
    private String field; 

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

    public Long getId() { 
     return id; 
    } 

    public String getField() { 
     return field; 
    } 

} 

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

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

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

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


    return beans; 
} 

}

+0

我測試了你的選擇,它運行良好。但是有一個問題。你看我有vaadin spring應用程序,並且這個假設將這個beanItemContainer附加到模態窗口。所以我需要在用戶導航到模態窗口時從數據庫預加載bean。我試圖使用@PostConstruct,但它什麼也沒做(或者我弄錯了)。非常感謝 – Reborn

+0

我的方法沒有看到任何問題。它應該工作。大概你可以分享一些代碼。 –

+0

不幸的是,我不能讓代碼atm,但是當它完成時我會告訴你。敬請期待。 – Reborn

1

如果我理解正確的問題combo.getValue()應該給你爲myBean相對於當前選擇的實例(如果沒有選擇項目,則爲null)

+0

是的,你理解錯了我的問題。然而'combo.getValue()'返回'Object'對象,這是很難轉換爲長問題。但一旦完成,我有一些與數據持久性有關的問題 - 1)它寫入所選項目的數據庫標題或...(我試圖將tresspass轉換爲long)toString)整行(帶有id和其他相關內容) – Reborn