有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查TreeView JavaFX中的所有CheckBoxTreeCells

我创建了一个TreeView,其中包含许多CheckBoxTreeCells。我还有一个Button,我想检查所有的CheckBoxTreeCells。我一直在读this tutorial,我有点迷路了。以下是我目前掌握的情况:

按钮代码:

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代码:

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);
}

链接中提供的示例比我需要的要复杂一些,我觉得这让我很困惑。如何在树视图中编辑CheckBoxTreeItems


共 (2) 个答案

  1. # 1 楼答案

    我能找到的最好办法就是:

    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);
            }
        }
    }
    
  2. # 2 楼答案

    除非有独立的CheckBoxTreeItem,否则选择根就足够了:

    root.setSelected(true);
    

    因为这会自动选择子对象