0

I have created a TreeView that contains many CheckBoxTreeCells. I also have a Button that I would like to check all of the CheckBoxTreeCells. I've been reading this tutorial, and I am a bit lost. Here is what I have so far:

Button Code:

public void fooMethod() {
    /*selectAll is an instance variable*/
    selectAll = new Button("Select All");
    selectAll.setOnMouseClicked(e -> handleSelectAllButtonAction(e));
}

private void handlSelectAllButtonAction(MouseEvent e) {
    /*Code goes here*/
}

TreeView Code:

public void fooMethod2() {
    /*myTreeView is also an insance variable*/
    myTreeView = new TreeView<String>();

    CheckBoxTreeItem<String> root = new CheckBoxTreeItem<>();
    CheckBoxTreeItem<String> branch1 = new CheckBoxTreeItem<>("Branch 1");
    CheckBoxTreeItem<String> branch2 = new CheckBoxTreeItem<>("Branch 2");
    CheckBoxTreeItem<String> branch3 = new CheckBoxTreeItem<>("Branch 3");

    root.getChildren.add(branch1);
    root.getChildren.add(branch2);
    root.getChildren.add(branch3);

    myTreeView.setCellFactory(CheckBoxTreeCell.forTreeView());
    myTreeView.setRoot(root);
    myTreeView.setShowRoot(false);
    myTreeView.setEditable(true);
}

The example provided in the link is a bit more complex than what I need, and I think it is confusing me. How do I edit a CheckBoxTreeItems in a TreeView?

mpowell48
  • 43
  • 8
  • [Here is a link to iterate through treeview in javafx. Hope this helps.](http://stackoverflow.com/questions/28342309/iterate-treeview-nodes) – Naveed Khan Nov 29 '16 at 22:48
  • This is what I tried first, but you can't check or uncheck boxes this way, because you get back a list of TreeItems instead of a list of CheckBoxTreeItems. Thank you though. – mpowell48 Nov 29 '16 at 22:53

2 Answers2

0

Best way I could find was to do this:

private void handlSelectAllButtonAction(MouseEvent e) {
    CheckBoxTreeItem<String> root = (CheckBoxTreeItem<String>)myTreeView.getRoot();
    int numBranches = root.getChildren().size();

    for(int i = 0; i < numBranches; i++) {
        if(((CheckBoxTreeItem<String>)root.getChildren().get(i)).isSelected()) {
            ((CheckBoxTreeItem<String>)root.getChildren().get(i)).setSelected(false);
        }
    }
}
mpowell48
  • 43
  • 8
0

Unless there are independent CheckBoxTreeItems, its enough to select the root:

root.setSelected(true);

since this automatically selects the children.

fabian
  • 80,457
  • 12
  • 86
  • 114
  • This would have been easier for selecting all of the checkboxes, so you get best answer. I implemented it differently, because I had another button that looped through the tree to check if any of the branches were indeterminate (the branches have leaves and I need to check if the leaves are checked if the branch is indeterminate). Full code for your answer should look like: `CheckBoxTreeItem root = (CheckBoxTreeItem)myTreeView.getRoot();` `root.setSelected(true);` – mpowell48 Nov 30 '16 at 09:07