I am trying to use a "Select All" checkbox which should allow to select all checkboxes and similarly unselect all of them on unselecting that checkbox. It should also allow to deselect some of all items. The goal is to add all finally selected checkbox items in a List "selectedItems". But, somehow I am not able to get it working as expected. It is giving unpredictable selections (for example it is adding unselected items to list and not adding some of selected items). Below is snippet of code that I'm trying.
Can you take a look at it and help me to figure out the issue. Please let me know if there is any better way to achieve the desired result.
- Code: Select all
List<String> selectedItems = new ArrayList<String>();
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Select All", true);
DefaultMutableTreeNode box1 = new DefaultMutableTreeNode("CheckBox1", false);
DefaultMutableTreeNode box2 = new DefaultMutableTreeNode("CheckBox2", false);
DefaultMutableTreeNode box3 = new DefaultMutableTreeNode("CheckBox3", false);
DefaultMutableTreeNode box4 = new DefaultMutableTreeNode("CheckBox4", false);
root.add(box1);
root.add(box2);
root.add(box3);
root.add(box4);
CheckBoxTree tree = new CheckBoxTree(root);
tree.getCheckBoxTreeSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
TreePath[] paths = e.getPaths();
for (int i = 0; i < paths.length; i++) {
TreePath path = e.getPath();
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
if (e.isAddedPath(i)) {
if (selectedNode.toString().equals("Select All")) {
for (Enumeration en = selectedNode.children(); en.hasMoreElements();) {
if(!selectedItems.contains(en.nextElement().toString())) {
selectedItems.add(en.nextElement().toString());
}
}
}
if(!selectedItems.contains(selectedNode.toString())) {
selectedItems.add(selectedNode.toString());
}
}
else {
if (selectedNode.toString().equals("Select All")) {
for (Enumeration en = selectedNode.children(); en.hasMoreElements();) {
selectedItems.remove(en.nextElement().toString());
}
}
selectedItems.remove(selectedNode.toString());
}
}
}
});