vendredi 3 février 2017

JavaFX: Adding CTRL-click functionality to checkboxes of nested CheckBoxTreeItem[s]

I have a situation where a TreeView is being displayed, with two levels of entries (parents and children), like so:

root (invisible)
|_ parent item 1
   |_ child item 1-1
   |_ child item 1-2
|_ parent item 2
   |_ child item 2-1

These items are all standard CheckBoxTreeItems. What I want to do, is to have CTRL-clicking on a parent item's checkbox select a set of it's children, according to some function. For example, here I might want only the first child item (i.e. child item 1-1 and child item 2-1) in each child list to be selected upon CTRL-clicking the parent checkbox.

Is this possible? As far as I can see, there's no good way to access the checkbox and give it e.g. an onMouseClick event handler, which is the solution that would make sense to me.

The code for the example tree layout given above:

TreeViewTest.java

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.StackPane;
import javafx.stage.Stage;

public class TreeViewTest extends Application {

    @Override
    public void start(final Stage stage) {
        StackPane sceneRoot = new StackPane();

        // create the tree model
        CheckBoxTreeItem<String> parent1 = new CheckBoxTreeItem<>("parent 1");
        CheckBoxTreeItem<String> parent2 = new CheckBoxTreeItem<>("parent 2");
        CheckBoxTreeItem<String> child1_1 = new CheckBoxTreeItem<>("child 1-1");
        CheckBoxTreeItem<String> child1_2 = new CheckBoxTreeItem<>("child 1-2");
        CheckBoxTreeItem<String> child2_1 = new CheckBoxTreeItem<>("child 2-1");
        CheckBoxTreeItem<String> root = new CheckBoxTreeItem<>("root");

        // attach the nodes
        parent1.getChildren().addAll(child1_1, child1_2);
        parent2.getChildren().addAll(child2_1);
        root.getChildren().addAll(parent1, parent2);

        // display everything
        root.setExpanded(true);
        parent1.setExpanded(true);
        parent2.setExpanded(true);

        // create the treeView
        final TreeView<String> treeView = new TreeView<>();
        treeView.setShowRoot(false);
        treeView.setRoot(root);

        // set the cell factory
        treeView.setCellFactory(CheckBoxTreeCell.forTreeView());

        // display the tree
        sceneRoot.getChildren().addAll(treeView);
        Scene scene = new Scene(sceneRoot, 200, 200);
        stage.setScene(scene);
        stage.show();
    }

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

Aucun commentaire:

Enregistrer un commentaire