2017-07-06 40 views
0

我最近開始使用vaadin框架。如何將checkBox綁定到布爾屬性?

我有一個表單,其中包含一些textFields和一個複選框,我的問題是所有的字段都與它們的屬性綁定在一起期望checkbox ??。

這是形式:

public class ContactForm extends FormLayout { 

private Button save = new Button("Save", this::save); 
private Button delete = new Button("Delete", this::delete); 
private Button cancel = new Button("Cancel", this::cancel); 
private TextField firstName = new TextField("First name"); 
private TextField lastName = new TextField("Last name"); 
private TextField phone = new TextField("Phone"); 
private TextField email = new TextField("Email"); 
private DateField birthDate = new DateField("Birth date"); 
private CheckBox bookMarks = new CheckBox("BookMarks"); 

private Contact contact; 

// Easily bind forms to beans and manage validation and buffering 
private BeanFieldGroup<Contact> formFieldBindings; 

public ContactForm() { 
    configureComponents(); 
    buildLayout(); 
} 

private void configureComponents() {...} 

private void buildLayout() {...} 



void edit(Contact contact) { 

    this.contact = contact; 
    if (contact != null) { 
     // Bind the properties of the contact POJO to fields in this form 
     formFieldBindings = BeanFieldGroup.bindFieldsBuffered(contact, this); 

     delete.setVisible(contact.getId() != null); 
    } 

    setVisible(contact != null); 
} 

@Override 
public AddressbookUI getUI() { 
    return (AddressbookUI) super.getUI(); 
}} 

這是我的類聯繫人:

public class Contact implements Serializable, Cloneable { 

private Long id; 

private String firstName = ""; 
private String lastName = ""; 
private String phone = ""; 
private String email = ""; 
private Date birthDate; 
private Boolean bookMarks; 

// getters and setters 
... 
} 

我到底做錯了什麼?我應該手動綁定複選框字段嗎?

+0

至於我所知'默認狀態的複選框(未選中,FALSE).' – soorapadman

+0

,能得到任何問題? – soorapadman

+0

是的,當我檢查複選框並保存表單時什麼也沒有發生 –

回答

1

的解決方案是增加addValueChangeListener的複選框這樣的:

bookMarks.addValueChangeListener(event -> contact.setBookMarks(bookMarks.getValue())); 
1

您可以獲得值check boxonlistenter並明確設置對象。

bookMarks.addListener(new ValueChangeListener() { 
    public void valueChange(ValueChangeEvent event) { 

     contact.setBookMarks(checkbox1.getValue()); 
    } 
}); 

更多地瞭解複選框選中此link

+0

我使用vaddin 7,這個代碼只適用於vaadin 6,無論如何它可以幫助我感謝你的幫助:) –

+0

好吧,我會更新我的答案,並upvote你也是。 – soorapadman

1

我認爲你需要使用formFieldBindings BeanFieldGroup你」已創建。因此,改變這一行

formFieldBindings = BeanFieldGroup.bindFieldsBuffered(contact, this); 

formFieldBindings = new BeanFieldGroup<Contact>(Contact.class); 
formFieldBindings.setItemDataSource(contact); 
formFieldBindings.buildAndBindMemberFields(this); 
+0

我試過你的解決方案,但不工作複選框仍然沒有約束力。但是,如果我添加一個偵聽器,它就可以工作。 –

+0

可能有必要將bean更改爲使用原始布爾值。這可能是它沒有正確綁定的原因。 –

+0

問題來自CheckBox組件,我已經使用原始布爾值但徒勞無功。 –

相關問題