1

我有一个树视图。我已将上下文菜单添加到树中的项目中,并通过添加节点来对菜单选择做出反应。由于某种原因,我第一次单击上下文菜单时,菜单并没有消失,TreeView UI 也没有更新。如果我再次单击上下文菜单消失,树中添加了 2 个项目。如果我再次进入上下文菜单并单击它通常会在以后每次添加 1 个项目。有什么建议吗?

我使用 TreeItem.getChildren().add() 添加子 TreeItems。这是创建 TreeCell 工厂的代码(创建上下文菜单。

public NodeTreeView(NodeView rootNodeView) {
    setRoot(rootNodeView);
    setCellFactory(new Callback<TreeView<String>,TreeCell<String>>() {
        @Override
        public TreeCell<String> call(TreeView<String> p) {
            return new TextFieldTreeCellImpl();
        }
    });
    getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
    getSelectionModel().selectedItemProperty().addListener(this);
}

@Override
public void changed(
        ObservableValue<? extends TreeItem<String>> ov,
        TreeItem<String> deselectedTreeItem,
        TreeItem<String> selectedTreeItem) {
    NodeView nodeView = null;

    nodeView = (NodeView) selectedTreeItem;
    System.out.println("Display properties for " + nodeView.getController().getType());
}

private final class TextFieldTreeCellImpl extends TreeCell<String> {

    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            NodeMenuController nodeMenuController = null;

            nodeMenuController = new NodeMenuController(getController());
            setText(getString());
            setGraphic(getTreeItem().getGraphic());
            setContextMenu(nodeMenuController.getView());
    }

最后,这是菜单项的构建方式:

public class NodeMenuController {

private NodeController nodeController;

public NodeMenuController(NodeController controller) {
    this.nodeController = controller;
}

public ContextMenu getView() {
    ContextMenu contextMenu = null;

    contextMenu = new ContextMenu();
    if (ChildMap.hasAllowedChildren(nodeController.getType())) {
        contextMenu.getItems().add(getAddChildMenuItem());
    }
    return contextMenu;
}

private MenuItem getAddChildMenuItem() {
    Menu         menu             = null;
    List<String> allowedChildList = null;

    menu = new Menu("+ Child");
    allowedChildList = ChildMap.get(nodeController.getType());
    for (final String allowedChildType : allowedChildList) {
        MenuItem menuItem = null;

        menuItem = new MenuItem(allowedChildType);
        menuItem.setOnAction(new EventHandler() {
            @Override
            public void handle(Event t) {
                NodeController newNodeController = null;

                newNodeController = new NodeController(new NodeModel(allowedChildType));
                nodeController.add(newNodeController);
            }
        });
        menu.getItems().add(menuItem);
    }
    return menu;
}
}
4

1 回答 1

0

原来我在选择处理程序中有一个我没有注意到的 NullPointerException。如果有人有这个问题,那是一回事。

于 2012-10-10T14:18:14.893 回答