1
我有一個TreeView。我已經將上下文菜單添加到樹中的項目中,並且我通過添加節點來對菜單選擇做出反應。出於某種原因,第一次單擊上下文菜單時,菜單不會消失,TreeView UI也不會更新。如果我再次點擊,上下文菜單消失並且2個項目被添加到樹中。如果我再次進入上下文菜單並點擊它,則每隔一段時間正常添加1個項目。有什麼建議?JavaFX2 TreeItem在添加到TreeView時不顯示
我使用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;
}
}
u能提供'NodeMenuController'代碼? –
我加入了全NodeMenuController類。如果需要的話我可以去除一切的得到簡化的例子這證明了t他的問題。我只是覺得有人可能會用一個工作的例子來回答。 – Stinky
找不到任何錯誤。您可以嘗試將新節點創建包裝到'Platform.runLater()'中,以避免從上下文菜單處理程序 –