Dmytro Bondarenko
Dmytro Bondarenko

Reputation: 21

TreeView one-at-a-time hander on CheckBoxTreeItem changes

I'm beginner in JavaFX.

I need to make one-at-a-time handler for any changes in the check boxes for my TreeView. Now it works like it handles all selected nodes simultaneously.

Thanks for help. Here is my code:

    package sample;

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.CheckBoxTreeItem;
    import javafx.scene.control.TreeView;
    import javafx.scene.control.cell.CheckBoxTreeCell;
    import javafx.scene.layout.BorderPane;
    import javafx.stage.Stage;

    public class Main extends Application {

        @Override
        public void start(Stage primaryStage) throws Exception{
            BorderPane root = new BorderPane();
            root.setCenter(initTreeView());
            primaryStage.setTitle("Hello World");
            primaryStage.setScene(new Scene(root, 300, 275));

            primaryStage.show();
        }

        public TreeView initTreeView() {
            TreeView<String> treeView = new TreeView<>();
            treeView.setRoot(new CheckBoxTreeItem<>("123"));
            treeView.getRoot().addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), event -> System.out.println("hello"));
            treeView.setCellFactory(p -> new CheckBoxTreeCell<>());
            treeView.getRoot().getChildren().addAll(new CheckBoxTreeItem<>("1"),new CheckBoxTreeItem<>("2"), new CheckBoxTreeItem<>("3"));
            treeView.getRoot().getChildren().get(0).getChildren().addAll(new CheckBoxTreeItem<>("4"),new CheckBoxTreeItem<>("5"), new CheckBoxTreeItem<>("6"));
            treeView.getRoot().getChildren().get(1).getChildren().addAll(new CheckBoxTreeItem<>("7"),new CheckBoxTreeItem<>("8"), new CheckBoxTreeItem<>("9"));
            treeView.getRoot().getChildren().get(2).getChildren().addAll(new CheckBoxTreeItem<>("10"),new CheckBoxTreeItem<>("11"), new CheckBoxTreeItem<>("12"));
            return treeView;
        }


        public static void main(String[] args) {
            launch(args);
        }

    }

Upvotes: 1

Views: 89

Answers (1)

Sergey Grinev
Sergey Grinev

Reputation: 34528

Actually it works correctly. Your event handler is called once for every changed checkbox node. Just note that changing subnodes affects parent ones as well, so you get several event handles calls.

Try next code instead which prints the name of the affected checkbox:

    treeView.getRoot().addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), 
        event -> System.out.println("hello " + event.getTreeItem().getValue()));

For example, if you click on checkbox "5" you will get the following log:

hello 5
hello 1
hello 123

because all parent node have changed state as well (from unchecked to intermediate "-" state). If you click "6" after that only one checkbox is affected and output will be:

hello 6

Upvotes: 1

Related Questions