PDA

View Full Version : Select/deselect CheckBoxGroup via CheckBox



listirer
21 Mar 2012, 5:48 AM
I have a CheckBoxGroup of some CheckBox and another CheckBox for select/deselect all CheckBox of CheckBoxGroup.
How can I implements this?
My code have some bug:


public class CheckBoxGroupExample extends LayoutContainer {

private CheckBox a;
private CheckBox b;
private CheckBox c;
private CheckBox all;

@Override
protected void onRender(Element parent, int index) {
super.onRender(parent, index);

CheckBoxGroup groupCheck = new CheckBoxGroup();
groupCheck.setOrientation(Orientation.VERTICAL);

a = new CheckBox();
a.setBoxLabel("A");
a.addListener(Events.Change, new Listener<FieldEvent>() {

@Override
public void handleEvent(FieldEvent fe) {
manageAll();
}
});
groupCheck.add(a);

b = new CheckBox();
b.setBoxLabel("B");
b.addListener(Events.Change, new Listener<FieldEvent>() {

@Override
public void handleEvent(FieldEvent fe) {
manageAll();
}
});
groupCheck.add(b);

c = new CheckBox();
c.setBoxLabel("C");
c.addListener(Events.Change, new Listener<FieldEvent>() {

@Override
public void handleEvent(FieldEvent fe) {
manageAll();
}
});
groupCheck.add(c);

super.add(groupCheck);

all = new CheckBox();
all.setBoxLabel("Select/Deselect all");
all.addListener(Events.Change, new Listener<FieldEvent>() {

@Override
public void handleEvent(FieldEvent fe) {
Boolean checkedRaw = Boolean.valueOf(((CheckBox) fe.getField()).getRawValue());

boolean allSelected = false;
if (checkedRaw) {
allSelected = true;
}

a.setValue(allSelected);
b.setValue(allSelected);
c.setValue(allSelected);
}
});
super.add(all);
}

private void manageAll() {
if (a.getValue() && b.getValue() && c.getValue()) {
all.setRawValue("true");
} else {
all.setRawValue("false");
}
}
}


Thanks

listirer
27 Mar 2012, 12:45 AM
Problem fixed: I use setValue method disabling the firing change event for checkbox all, instead of setRawValue method.

The snipped code fix:


all.addListener(Events.Change, new Listener<FieldEvent>() {

@Override
public void handleEvent(FieldEvent fe) {
Boolean allSelected = (Boolean) fe.getValue();

a.setValue(allSelected);
b.setValue(allSelected);
c.setValue(allSelected);
}
});

...

private void manageAll() {
all..setFireChangeEventOnSetValue(false); // Disable the firing of Events.Change
if (a.getValue() && b.getValue() && c.getValue()) {
all.setValue(true);
} else {
all.setValue(false);
}
all.setFireChangeEventOnSetValue(true); // Enable the firing of Events.Change
}