禁用JavaFX中的所有父节点,同时使其所有子节点保持可点击状态

时间:2018-09-02 17:34:43

标签: java javafx treeview

我正在尝试创建一个具有复选框树项的JavaFX树视图。我要求所有具有子节点的节点都应禁用。但是这些节点的所有子节点都应该是可点击的。

基本上,如果树项是叶子,则应将其启用并单击。

这是我使用的当前代码。这会禁用带有子节点的节点,但是问题是,因为它被禁用,所以我无法访问父节点中的代码。

public class App extends Application
{
public static void main( String[] args )
{
    launch(args);
}

private List<Dependant> myList = new ArrayList();

@SuppressWarnings("unchecked")
@Override
public void start(Stage primaryStage) {

    CheckBoxTreeItem<String> rootItem = new CheckBoxTreeItem("Root");
    final List<CheckBoxTreeItem<String>> treeItems = new ArrayList(6);
    for (int i = 0; i < 6; i++) {
        CheckBoxTreeItem<String> item = new CheckBoxTreeItem("L0"+i+"");
        item.setIndependent(true);
        treeItems.add(item);  
        myList.add(new Dependant("0"+i+"", "type1"));
    }
    rootItem.getChildren().addAll(treeItems);

    rootItem.setExpanded(true);
    rootItem.setIndependent(true);
    CheckBoxTreeItem<String> rootItem2 = new CheckBoxTreeItem("folder");
    final List<CheckBoxTreeItem<String>> treeItems2 = new ArrayList(6);
    for (int i = 0; i < 6; i++) {
        CheckBoxTreeItem<String> item = new CheckBoxTreeItem("L1"+i+"");
        item.setIndependent(true);
        treeItems2.add(item); 
        myList.add(new Dependant("0"+i+"", "type2"));
    }
    rootItem2.getChildren().addAll(treeItems2);
    rootItem2.setIndependent(true);
    rootItem.getChildren().set(2,rootItem2);

    TreeView tree = new TreeView(rootItem);

    tree.setCellFactory((Object item) -> {

        final CheckBoxTreeCell<String> cell = new CheckBoxTreeCell();

        cell.itemProperty().addListener((obs,s,s1)->{

            cell.disableProperty().unbind();
            if(s1!=null && !s1.isEmpty()){
                BooleanProperty prop = new SimpleBooleanProperty();
                prop.set((s1.equals("folder")));
                cell.disableProperty().bind(prop);
            }
        });
        return cell;
    });

    tree.setRoot(rootItem);

    StackPane root = new StackPane();
    root.getChildren().add(tree);
    primaryStage.setScene(new Scene(root, 300, 250));
    primaryStage.show();
  }

}

这不是我的应用程序的最终代码,它只是我在完成最终实现之前尝试过的示例代码。

从代码中可以看到,由于方法isLeaf()不可用,单元格的disable属性绑定到名称是否等于“ folder”。

如果有人想知道为什么我需要禁用所有父节点,那是因为在最终实现中,我只需要在整个树视图中选择一项(因为单击父节点也将选择它的所有子节点!)。

谢谢。

1 个答案:

答案 0 :(得分:1)

虽然问题是一个典型的XY-problem(寻求解决通过试图以错误的方式解决实际需求而引入的问题),但真正的问题很有趣,可以快速尝试一下:)

据我了解,真正的要求:

  • 有一棵树,其中包含允许选择的项目(通过复选框)
  • 在任何时候都只能选择一个项目

一如既往,基本方法是将此类逻辑添加到通用模型中(相对于view =单元格)。对于Treeview,模型是treeItem-它本身无法处理项目间的逻辑,因此它需要具有更广泛知识的控制器。

幸运的是,fx支持多选一选: one 的角色由Toggle扮演,许多的角色由ToggleGroup扮演。现在,我们要做的就是将这种支持应用到我们的上下文中:

  • 实现作为Toggle的自定义TreeItem(以下示例扩展了CheckBoxTreeItem)
  • 在应用程序代码中使用该项目,并根据需要将其添加到ToggleGroups

一些代码示例(请注意:实现不完整且未经正式测试-只是为了指明方向!)

public class TreeSingleSelectedCheckboxWithToggle extends Application {

    /**
     * A custom CheckBoxTreeItem that implements Toggle.
     * 
     * To control which/how many items can be selected at any
     * time, add them to one or several ToggleGroups.
     * 
     * @author Jeanette Winzenburg, Berlin
     */
    public static class ToggleTreeItem<T> extends CheckBoxTreeItem<T>
        implements Toggle {


        public ToggleTreeItem() {
            super();
            init();
        }

        public ToggleTreeItem(T value) {
            super(value);
            init();
        }

        private void init() {
            // basically c&p from ToggleButton 
            selectedProperty().addListener(ov -> {
                final boolean selected = isSelected();
                final ToggleGroup tg = getToggleGroup();
                // Note: these changes need to be done before selectToggle/clearSelectedToggle since
                // those operations change properties and can execute user code, possibly modifying selected property again
                if (tg != null) {
                    if (selected) {
                        tg.selectToggle(ToggleTreeItem.this);
                    } else if (tg.getSelectedToggle() == ToggleTreeItem.this) {
                        // reflective access to package-private api  - use your own utility method
                        FXUtils.invokeMethod(ToggleGroup.class, tg, "clearSelectedToggle");
                       // tg.clearSelectedToggle();
                    }
                }

            });
        }
        /**
         * The {@link ToggleGroup} to which this {@code ToggleButton} belongs. A
         * {@code ToggleButton} can only be in one group at any one time. If the
         * group is changed, then the button is removed from the old group prior to
         * being added to the new group.
         */
        private ObjectProperty<ToggleGroup> toggleGroup;
        @Override
        public final void setToggleGroup(ToggleGroup value) {
            toggleGroupProperty().set(value);
        }

        @Override
        public final ToggleGroup getToggleGroup() {
            return toggleGroup == null ? null : toggleGroup.get();
        }

        @Override
        public final ObjectProperty<ToggleGroup> toggleGroupProperty() {
            if (toggleGroup == null) {
                toggleGroup = new ObjectPropertyBase<ToggleGroup>() {
                    private ToggleGroup old;
                    @Override protected void invalidated() {
                        final ToggleGroup tg = get();
                        if (tg != null && !tg.getToggles().contains(ToggleTreeItem.this)) {
                            if (old != null) {
                                old.getToggles().remove(ToggleTreeItem.this);
                            }
                            tg.getToggles().add(ToggleTreeItem.this);
                        } else if (tg == null) {
                            old.getToggles().remove(ToggleTreeItem.this);
                        }

                        old = tg;
                    }

                    @Override
                    public Object getBean() {
                        return ToggleTreeItem.this;
                    }

                    @Override
                    public String getName() {
                        return "toggleGroup";
                    }
                };
            }
            return toggleGroup;
        }
        @Override
        public Object getUserData() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void setUserData(Object value) {
            // TODO Auto-generated method stub
        }

        @Override
        public ObservableMap<Object, Object> getProperties() {
            // TODO Auto-generated method stub
            return null;
        }

    }

    @SuppressWarnings("unchecked")
    @Override
    public void start(Stage primaryStage) {

        ToggleGroup toggleGroup = new ToggleGroup();
        ToggleTreeItem<String> rootItem = new ToggleTreeItem<>("Root");
        toggleGroup.getToggles().add(rootItem);
        final List<ToggleTreeItem<String>> treeItems = new ArrayList<>(6);
        for (int i = 0; i < 6; i++) {
            ToggleTreeItem<String> item = new ToggleTreeItem<>("L0" + i + "");
            item.setIndependent(true);
            treeItems.add(item);
            toggleGroup.getToggles().add(item);
            myList.add(new Dependant("0" + i + "", "type1"));
        }
        rootItem.getChildren().addAll(treeItems);

        rootItem.setExpanded(true);
        rootItem.setIndependent(true);
        ToggleTreeItem<String> rootItem2 = new ToggleTreeItem<>("folder");
        toggleGroup.getToggles().add(rootItem2);
        final List<ToggleTreeItem<String>> treeItems2 = new ArrayList<>(6);
        for (int i = 0; i < 6; i++) {
            ToggleTreeItem<String> item = new ToggleTreeItem<>("L1" + i + "");
            item.setIndependent(true);
            treeItems2.add(item);
            toggleGroup.getToggles().add(item);
            myList.add(new Dependant("0" + i + "", "type2"));
        }
        rootItem2.getChildren().addAll(treeItems2);
        rootItem2.setIndependent(true);
        rootItem.getChildren().set(2, rootItem2);

        TreeView tree = new TreeView<>(rootItem);

        tree.setCellFactory(CheckBoxTreeCell.forTreeView());

        tree.setRoot(rootItem);

        StackPane root = new StackPane();
        root.getChildren().add(tree);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

    public static class Dependant {

        String one;
        String two;
        public Dependant(String one, String two) {
            this.one = one;
            this.two = two;
        }

    }

    private List<Dependant> myList = new ArrayList();


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

}