Raguram
Raguram

Reputation: 157

How to make child Tree Items checked/un-checked if parent Tree was made checked/un-checked

I'm having a Check-box Tree View structure, consisting of parent and child nodes.

I want to make all the child nodes [of the parent node] appear as checked if parent Tree is checked. Similarly, if parent Tree is unchecked then its childrens should be unchecked.

Upvotes: 2

Views: 4078

Answers (1)

Monikka
Monikka

Reputation: 528

The best way to achieve this would be using the JFace CheckboxTreeViewer as it has the following predefined methods to simplify the task.

  1. setSubtreeChecked - Sets the child elements checked on selecting the parent node
  2. getCheckedElements - Gets all the checked tree elements

    final CheckboxTreeViewer treeViewer = new CheckboxTreeViewer(parent);
    
    // When user checks a checkbox in the tree, check all its children
    treeViewer.addCheckStateListener(new ICheckStateListener() {
    public void checkStateChanged(CheckStateChangedEvent event) {
        // If the item is checked . . .
        if (event.getChecked()) {
          // . . . check all its children
          treeViewer.setSubtreeChecked(event.getElement(), true);
        }
      }
    });
    
    // Get the selected elements from the tree
    Object[] actuallyChecked = treeViewer.getCheckedElements();
    

Upvotes: 4

Related Questions