如何将checkBox绑定到布尔属性?

时间:2017-07-06 11:15:23

标签: java checkbox vaadin vaadin7

我最近开始使用vaadin框架。

我有一个包含一些textFields和一个复选框的Form,我的问题是所有字段都绑定了它们的属性expect 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
...
}

我做错了什么?我应该手动绑定复选框字段吗?

3 个答案:

答案 0 :(得分:1)

您可以获取check boxonlistenter的值并明确设置对象。

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

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

要了解有关复选框的详情,请查看此link

答案 1 :(得分:1)

解决方案是在复选框中添加addValueChangeListener,如下所示:

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

答案 2 :(得分:1)

我认为您需要使用您已创建的formFieldBindings BeanFieldGroup。所以改变这一行

 formFieldBindings = BeanFieldGroup.bindFieldsBuffered(contact, this);

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